阿里资深工程师教你如何优化 Java 代码!
以下文章来源于阿里巴巴中间件 ,作者王超
明代王阳明先生在《传习录》谈为学之道时说:
私欲日生,如地上尘,一日不扫,便又有一层。着实用功,便见道无终穷,愈探愈深,必使精白无一毫不彻方可。
for (String key : map.keySet()) {
String value = map.get(key);
...
}
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
...
}
...
}
...
}
list.add("Hello");
list.add("World");
if (list.containsAll(list)) { // 无意义,总是返回true
...
}
list.removeAll(list); // 性能差, 直接使用clear()
List<Integer> list = new ArrayList<>();
for (int i : arr) {
list.add(i);
}
List<Integer> list = new ArrayList<>(arr.length);
for (int i : arr) {
list.add(i);
}
for (int i = 0; i < 10; i++) {
s += i;
}
String b = "b";
String c = "c";
String s = a + b + c; // 没问题,java编译器会进行优化
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
sb.append(i); // 循环中,java编译器无法进行优化,所以要手动使用StringBuilder
}
List<Integer> list = otherService.getList();
if (list instanceof RandomAccess) {
// 内部数组实现,可以随机访问
System.out.println(list.get(list.size() - 1));
} else {
// 内部可能是链表实现,随机访问效率低
}
频繁调用 Collection.contains 方法请使用 Set
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
// 时间复杂度O(n)
list.contains(i);
}
正例:
ArrayList<Integer> list = otherService.getList();
Set<Integer> set = new HashSet(list);
for (int i = 0; i <= Integer.MAX_VALUE; i++) {
// 时间复杂度O(1)
set.contains(i);
}
让代码更优雅
长整型常量后添加大写 L
long value = 1l;
long max = Math.max(1L, 5);
正例:
long max = Math.max(1L, 5L);
...
}
if (a == 100) {
...
}
for (int i = 0; i < MAX_COUNT; i++){
...
}
if (count == MAX_COUNT) {
...
}
{
put("a", 1);
put("b", 2);
}
};
private static List<String> list = new ArrayList<String>() {
{
add("a");
add("b");
}
};
static {
map.put("a", 1);
map.put("b", 2);
};
private static List<String> list = new ArrayList<>();
static {
list.add("a");
list.add("b");
};
private void handle(String fileName) {
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(fileName));
while ((line = reader.readLine()) != null) {
...
}
} catch (Exception e) {
...
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
...
}
}
}
}
正例:
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
...
}
} catch (Exception e) {
...
}
}
private int unusedField = 100;
private void unusedMethod() {
...
}
public int sum(int a, int b) {
return a + b;
}
}
public class DoubleDemo1 {
public int sum(int a, int b) {
return a + b;
}
}
int c = 100;
return a + b;
}
return a + b;
}
删除未使用的方法参数
未使用的方法参数具有误导性,删除未使用的方法参数,使代码更简洁更易维护。但是,由于重写方法是基于父类或接口的方法定义,即便有未使用的方法参数,也是不能删除的。
return a + b;
}
return a + b;
}
return (x + 2);
int x = (y * 3) + 1;
int m = (n * 4 + 2);
return x + 2;
int x = y * 3 + 1;
int m = n * 4 + 2;
public static final double PI = 3.1415926D;
public static int sum(int a, int b) {
return a + b;
}
}
public static final double PI = 3.1415926D;
private MathUtils() {}
public static int sum(int a, int b) {
return a + b;
}
}
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (Exception e) {
throw e;
}
}
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
StringBuilder builder = new StringBuilder();
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
}
public static final String CONST_NAME = "name";
...
}
User user = new User();
String nameKey = user.CONST_NAME;
public static final String CONST_NAME = "name";
...
}
String nameKey = User.CONST_NAME;
try {
return user.getName();
} catch (NullPointerException e) {
return null;
}
}
if (Objects.isNull(user)) {
return null;
}
return user.getName();
}
使用String.valueOf(value)代替""+value
当要把其它对象或类型转化为字符串时,使用 String.valueOf(value) 比""+value 的效率更高。
String s = "" + i;
String s = String.valueOf(i);
正例:
/**
* 保存
*
* @deprecated 此方法效率较低,请使用{@link newSave()}方法替换它
*/
@Deprecated
public void save(){
// do something
}
让代码远离 Bug
禁止使用构造方法 BigDecimal(double)
return null;
}
public static List<Result> getResultList() {
return null;
}
public static Map<String, Result> getResultMap() {
return null;
}
public static void main(String[] args) {
Result[] results = getResults();
if (results != null) {
for (Result result : results) {
...
}
}
List<Result> resultList = getResultList();
if (resultList != null) {
for (Result result : resultList) {
...
}
}
Map<String, Result> resultMap = getResultMap();
if (resultMap != null) {
for (Map.Entry<String, Result> resultEntry : resultMap) {
...
}
}
}
return new Result[0];
}
public static List<Result> getResultList() {
return Collections.emptyList();
}
public static Map<String, Result> getResultMap() {
return Collections.emptyMap();
}
public static void main(String[] args) {
Result[] results = getResults();
for (Result result : results) {
...
}
List<Result> resultList = getResultList();
for (Result result : resultList) {
...
}
Map<String, Result> resultMap = getResultMap();
for (Map.Entry<String, Result> resultEntry : resultMap) {
...
}
}
return status.equals(OrderStatus.FINISHED); // 可能抛空指针异常
}
return OrderStatus.FINISHED.equals(status);
}
public void isFinished(OrderStatus status) {
return Objects.equals(status, OrderStatus.FINISHED);
}
DISABLED(0, "禁用"),
ENABLED(1, "启用");
public int value;
private String description;
private UserStatus(int value, String description) {
this.value = value;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
DISABLED(0, "禁用"),
ENABLED(1, "启用");
private final int value;
private final String description;
private UserStatus(int value, String description) {
this.value = value;
this.description = description;
}
public int getValue() {
return value;
}
public String getDescription() {
return description;
}
}
"a|ab|abc".split("|"); // 结果为["a", "|", "a", "b", "|", "a", "b", "c"]
正例:
"a.ab.abc".split("\\."); // 结果为["a", "ab", "abc"]
"a|ab|abc".split("\\|"); // 结果为["a", "ab", "abc"]
这篇文章,可以说是从事 Java 开发的经验总结,分享出来以供大家参考。希望能帮大家避免踩坑,让代码更加高效优雅。
随着物联网迅速兴起,互联网和智能硬件厂商纷纷开始构建物联网基础平台,基础平台在性能、稳定性和灵活的可扩展性方面正面临着诸多挑战。百度天工基础平台边云融合技术负责人深度揭秘百度天工IoT基础平台的主要技术框架以及在微服务容器化改造实践过程中的工程实现细节。
技术干货来袭!立即扫码报名!
热 文 推 荐
☞任正非称华为 6G 领先世界;支付宝小程序将与微博打通;Linux Kernel 5.3 发布 | 极客头条
☞我在快手认识了 4 位工程师,看到了快速发展的公司和员工如何彼此成就!