IDC

这些提高你代码性能的技巧你值得拥有

作者:admin 2021-04-24 我要评论

1.让代码性能更高 1.1.需要 Map 的主键和取值时,应该迭代 entrySet() 当循环中只需要 Map 的主键时,迭代 keySet() 是正确的。但是,当需要主键和取值时,迭代 ...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

 1.让代码性能更高

1.1.需要 Map 的主键和取值时,应该迭代 entrySet()

当循环中只需要 Map 的主键时,迭代 keySet() 是正确的。但是,当需要主键和取值时,迭代 entrySet() 才是更高效的做法,比先迭代 keySet() 后再去 get 取值性能更佳。

反例:

  1. Map<String, String> map = ...; 
  2. for (String key : map.keySet()) { 
  3.     String value = map.get(key); 
  4.     ... 

 正例:

  1. Map<String, String> map = ...; 
  2. for (Map.Entry<String, String> entry : map.entrySet()) { 
  3.     String key = entry.getKey(); 
  4.     String value = entry.getValue(); 
  5.     ... 

 1.2.应该使用 Collection.isEmpty() 检测空

使用 Collection.size() 来检测空逻辑上没有问题,但是使用 Collection.isEmpty() 使得代码更易读,并且可以获得更好的性能。任何 Collection.isEmpty() 实现的时间复杂度都是 O(1) ,但是某些 Collection.size() 实现的时间复杂度可能是O(n)。

反例:

  1. if (collection.size() == 0) { 
  2.     ... 

 正例:

  1. if (collection.isEmpty()) { 
  2.     ... 

如果需要还需要检测 null ,可采用 CollectionUtils.isEmpty(collection) 和

CollectionUtils.isNotEmpty(collection)。

1.3.不要把集合对象传给自己

将集合作为参数传递给集合自己的方法要么是一个错误,要么是无意义的代码。

此外,由于某些方法要求参数在执行期间保持不变,因此将集合传递给自身可能会导致异常行为。

反例:

  1. List<String> list = new ArrayList<>(); 
  2. list.add("Hello"); 
  3. list.add("World"); 
  4. if (list.containsAll(list)) { // 无意义,总是返回true 
  5.     ... 
  6. list.removeAll(list); // 性能差, 直接使用clear() 

 1.4.集合初始化尽量指定大小

java 的集合类用起来十分方便,但是看源码可知,集合也是有大小限制的。每次扩容的时间复杂度很有可能是 O(n) ,所以尽量指定可预知的集合大小,能减少集合的扩容次数。

反例:

  1. int[] arr = new int[]{1, 2, 3}; 
  2. List<Integer> list = new ArrayList<>(); 
  3. for (int i : arr) { 
  4.     list.add(i); 

 正例:

  1. int[] arr = new int[]{1, 2, 3}; 
  2. List<Integer> list = new ArrayList<>(arr.length); 
  3. for (int i : arr) { 
  4.     list.add(i); 

 1.5.字符串拼接使用 StringBuilder

一般的字符串拼接在编译期 java 会进行优化,但是在循环中字符串拼接,java 编译期无法做到优化,所以需要使用 StringBuilder 进行替换。

反例:

  1. String s = ""
  2. for (int i = 0; i < 10; i++) { 
  3.     s += i; 

 正例:

  1. String a = "a"
  2. String b = "b"
  3. String c = "c"
  4. String s = a + b + c; // 没问题,java编译器会进行优化 
  5. StringBuilder sb = new StringBuilder(); 
  6. for (int i = 0; i < 10; i++) { 
  7.     sb.append(i);  // 循环中,java编译器无法进行优化,所以要手动使用StringBuilder 

 1.6.List的随机访问

大家都知道数组和链表的区别:数组的随机访问效率更高。当调用方法获取到 List 后,如果想随机访问其中的数据,并不知道该数组内部实现是链表还是数组,怎么办呢?可以判断它是否实现 RandomAccess 接口。

正例:

  1. // 调用别人的服务获取到list 
  2. List<Integer> list = otherService.getList(); 
  3. if (list instanceof RandomAccess) { 
  4.     // 内部数组实现,可以随机访问 
  5.     System.out.println(list.get(list.size() - 1)); 
  6. else { 
  7.     // 内部可能是链表实现,随机访问效率低 

 1.7.频繁调用 Collection.contains 方法请使用 Set

在 java 集合类库中,List 的 contains 方法普遍时间复杂度是 O(n) ,如果在代码中需要频繁调用 contains 方法查找数据,可以先将 list 转换成 HashSet 实现,将 O(n) 的时间复杂度降为 O(1) 。

反例:

  1. ArrayList<Integer> list = otherService.getList(); 
  2. for (int i = 0; i <= Integer.MAX_VALUE; i++) { 
  3.     // 时间复杂度O(n) 
  4.     list.contains(i); 

 正例:

  1. ArrayList<Integer> list = otherService.getList(); 
  2. Set<Integerset = new HashSet(list); 
  3. for (int i = 0; i <= Integer.MAX_VALUE; i++) { 
  4.     // 时间复杂度O(1) 
  5.     set.contains(i); 

 2.让代码更优雅

2.1.长整型常量后添加大写 L

在使用长整型常量值时,后面需要添加 L ,必须是大写的 L ,不能是小写的 l ,小写 l 容易跟数字 1 混淆而造成误解。

反例:

  1. long value = 1l; 
  2. long max = Math.max(1L, 5); 

 正例:

  1. long value = 1L; 
  2. long max = Math.max(1L, 5L); 

 2.2.不要使用魔法值

当你编写一段代码时,使用魔法值可能看起来很明确,但在调试时它们却不显得那么明确了。这就是为什么需要把魔法值定义为可读取常量的原因。但是,-1、0 和 1 不被视为魔法值。

反例:

  1. for (int i = 0; i < 100; i++){ 
  2.     ... 
  3. if (a == 100) { 
  4.     ... 

 正例:

  1. private static final int MAX_COUNT = 100; 
  2. for (int i = 0; i < MAX_COUNT; i++){ 
  3.     ... 
  4. if (count == MAX_COUNT) { 
  5.     ... 

 2.3.不要使用集合实现来赋值静态成员变量

对于集合类型的静态成员变量,不要使用集合实现来赋值,应该使用静态代码块赋值。

反例:

  1. private static Map<String, Integer> map = new HashMap<String, Integer>() { 
  2.     { 
  3.         put("a", 1); 
  4.         put("b", 2); 
  5.     } 
  6. }; 
  7.  
  8. private static List<String> list = new ArrayList<String>() { 
  9.     { 
  10.         add("a"); 
  11.         add("b"); 
  12.     } 
  13. }; 

正例:

  1. private static Map<String, Integer> map = new HashMap<>(); 
  2. static { 
  3.     map.put("a", 1); 
  4.     map.put("b", 2); 
  5. }; 
  6.  
  7. private static List<String> list = new ArrayList<>(); 
  8. static { 
  9.     list.add("a"); 
  10.     list.add("b"); 
  11. }; 

 2.4.建议使用 try-with-resources 语句

Java 7 中引入了 try-with-resources 语句,该语句能保证将相关资源关闭,优于原来的 try-catch-finally 语句,并且使程序代码更安全更简洁。

反例:

  1. private void handle(String fileName) { 
  2.     BufferedReader reader = null
  3.     try { 
  4.         String line; 
  5.         reader = new BufferedReader(new FileReader(fileName)); 
  6.         while ((line = reader.readLine()) != null) { 
  7.             ... 
  8.         } 
  9.     } catch (Exception e) { 
  10.         ... 
  11.     } finally { 
  12.         if (reader != null) { 
  13.             try { 
  14.                 reader.close(); 
  15.             } catch (IOException e) { 
  16.                 ... 
  17.             } 
  18.         } 
  19.     } 

 正例:

  1. private void handle(String fileName) { 
  2.     try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { 
  3.         String line; 
  4.         while ((line = reader.readLine()) != null) { 
  5.             ... 
  6.         } 
  7.     } catch (Exception e) { 
  8.         ... 
  9.     } 

 2.5.删除未使用的私有方法和字段

删除未使用的私有方法和字段,使代码更简洁更易维护。若有需要再使用,可以从历史提交中找回。

反例:

  1. public class DoubleDemo1 { 
  2.     private int unusedField = 100; 
  3.     private void unusedMethod() { 
  4.         ... 
  5.     } 
  6.     public int sum(int a, int b) { 
  7.         return a + b; 
  8.     } 

 正例:

  1. public class DoubleDemo1 { 
  2.     public int sum(int a, int b) { 
  3.         return a + b; 
  4.     } 

 2.6.删除未使用的局部变量

删除未使用的局部变量,使代码更简洁更易维护。

反例:

  1. public int sum(int a, int b) { 
  2.     int c = 100; 
  3.     return a + b; 

 正例:

  1. public int sum(int a, int b) { 
  2.     return a + b; 

 2.7.删除未使用的方法参数

未使用的方法参数具有误导性,删除未使用的方法参数,使代码更简洁更易维护。但是,由于重写方法是基于父类或接口的方法定义,即便有未使用的方法参数,也是不能删除的。

反例:

  1. public int sum(int a, int b, int c) { 
  2.     return a + b; 

 正例:

  1. public int sum(int a, int b) { 
  2.     return a + b; 

 2.8.删除表达式的多余括号

对应表达式中的多余括号,有人认为有助于代码阅读,也有人认为完全没有必要。对于一个熟悉 Java 语法的人来说,表达式中的多余括号反而会让代码显得更繁琐。

反例:

  1. return (x); 
  2. return (x + 2); 
  3. int x = (y * 3) + 1; 
  4. int m = (n * 4 + 2); 

 正例:

  1. return x; 
  2. return x + 2; 
  3. int x = y * 3 + 1; 
  4. int m = n * 4 + 2; 

 2.9.工具类应该屏蔽构造函数

工具类是一堆静态字段和函数的集合,不应该被实例化。但是, Java 为每个没有明确定义构造函数的类添加了一个隐式公有构造函数。所以,为了避免 java "小白"使用有误,应该显式定义私有构造函数来屏蔽这个隐式公有构造函数。

反例:

  1. public class MathUtils { 
  2.     public static final double PI = 3.1415926D; 
  3.     public static int sum(int a, int b) { 
  4.         return a + b; 
  5.     } 

 正例:

  1. public class MathUtils { 
  2.     public static final double PI = 3.1415926D; 
  3.     private MathUtils() {} 
  4.     public static int sum(int a, int b) { 
  5.         return a + b; 
  6.     } 

 2.10.删除多余的异常捕获并抛出

用catch语句捕获异常后,什么也不进行处理,就让异常重新抛出,这跟不捕获异常的效果一样,可以删除这块代码或添加别的处理。

反例:

  1. private static String readFile(String fileName) throws IOException { 
  2.     try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { 
  3.         String line; 
  4.         StringBuilder builder = new StringBuilder(); 
  5.         while ((line = reader.readLine()) != null) { 
  6.             builder.append(line); 
  7.         } 
  8.         return builder.toString(); 
  9.     } catch (Exception e) { 
  10.         throw e; 
  11.     } 

 正例:

  1. private static String readFile(String fileName) throws IOException { 
  2.     try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { 
  3.         String line; 
  4.         StringBuilder builder = new StringBuilder(); 
  5.         while ((line = reader.readLine()) != null) { 
  6.             builder.append(line); 
  7.         } 
  8.         return builder.toString(); 
  9.     } 

 2.11.公有静态常量应该通过类访问

虽然通过类的实例访问公有静态常量是允许的,但是容易让人它误认为每个类的实例都有一个公有静态常量。所以,公有静态常量应该直接通过类访问。

反例:

  1. public class User { 
  2.     public static final String CONST_NAME = "name"
  3.     ... 
  4.  
  5. User user = new User(); 
  6. String nameKey = user.CONST_NAME; 

 正例:

  1. public class User { 
  2.     public static final String CONST_NAME = "name"
  3.     ... 
  4.  
  5. String nameKey = User.CONST_NAME; 

 2.12.不要用 NullPointerException 判断空

空指针异常应该用代码规避(比如检测不为空),而不是用捕获异常的方式处理。

反例:

  1. public String getUserName(User user) { 
  2.     try { 
  3.         return user.getName(); 
  4.     } catch (NullPointerException e) { 
  5.         return null
  6.     } 

 正例:

  1. public String getUserName(User user) { 
  2.     if (Objects.isNull(user)) { 
  3.         return null
  4.     } 
  5.     return user.getName(); 

 2.13.使用 String.valueOf(value) 代替 ""+value

当要把其它对象或类型转化为字符串时,使用 String.valueOf(value) 比 ""+value 的效率更高。

反例:

  1. int i = 1; 
  2. String s = "" + i; 

 正例:

  1. int i = 1; 
  2. String s = String.valueOf(i); 

 2.14.过时代码添加 @Deprecated 注解

当一段代码过时,但为了兼容又无法直接删除,不希望以后有人再使用它时,可以添加 @Deprecated 注解进行标记。在文档注释中添加 @deprecated 来进行解释,并提供可替代方案

正例:

  1. /** 
  2.  * 保存 
  3.  * 
  4.  * @deprecated 此方法效率较低,请使用{@link newSave()}方法替换它 
  5.  */ 
  6. @Deprecated 
  7. public void save(){ 
  8.     // do something 

 3.让代码远离 bug

3.1.禁止使用构造方法 BigDecimal(double)

BigDecimal(double) 存在精度损失风险,在精确计算或值比较的场景中可能会导致业务逻辑异常。

反例:

  1. BigDecimal value = new BigDecimal(0.1D); // 0.100000000000000005551115... 

正例:

  1. BigDecimal value = BigDecimal.valueOf(0.1D);; // 0.1 

3.2.返回空数组和空集合而不是 null

返回 null ,需要调用方强制检测 null ,否则就会抛出空指针异常。返回空数组或空集合,有效地避免了调用方因为未检测 null 而抛出空指针异常,还可以删除调用方检测 null 的语句使代码更简洁。

反例:

  1. public static Result[] getResults() { 
  2.     return null
  3.  
  4. public static List<Result> getResultList() { 
  5.     return null
  6.  
  7. public static Map<String, Result> getResultMap() { 
  8.     return null
  9.  
  10. public static void main(String[] args) { 
  11.     Result[] results = getResults(); 
  12.     if (results != null) { 
  13.         for (Result result : results) { 
  14.             ... 
  15.         } 
  16.     } 
  17.  
  18.     List<Result> resultList = getResultList(); 
  19.     if (resultList != null) { 
  20.         for (Result result : resultList) { 
  21.             ... 
  22.         } 
  23.     } 
  24.  
  25.     Map<String, Result> resultMap = getResultMap(); 
  26.     if (resultMap != null) { 
  27.         for (Map.Entry<String, Result> resultEntry : resultMap) { 
  28.             ... 
  29.         } 
  30.     } 

 正例:

  1. public static Result[] getResults() { 
  2.     return new Result[0]; 
  3.  
  4. public static List<Result> getResultList() { 
  5.     return Collections.emptyList(); 
  6.  
  7. public static Map<String, Result> getResultMap() { 
  8.     return Collections.emptyMap(); 
  9.  
  10. public static void main(String[] args) { 
  11.     Result[] results = getResults(); 
  12.     for (Result result : results) { 
  13.         ... 
  14.     } 
  15.  
  16.     List<Result> resultList = getResultList(); 
  17.     for (Result result : resultList) { 
  18.         ... 
  19.     } 
  20.  
  21.     Map<String, Result> resultMap = getResultMap(); 
  22.     for (Map.Entry<String, Result> resultEntry : resultMap) { 
  23.         ... 
  24.     } 

 3.3.优先使用常量或确定值来调用 equals 方法

对象的 equals 方法容易抛空指针异常,应使用常量或确定有值的对象来调用 equals 方法。当然,使用java.util.Objects.equals() 方法是最佳实践。

反例:

  1. public void isFinished(OrderStatus status) { 
  2.     return status.equals(OrderStatus.FINISHED); // 可能抛空指针异常 

 正例:

  1. public void isFinished(OrderStatus status) { 
  2.     return OrderStatus.FINISHED.equals(status); 
  3.  
  4. public void isFinished(OrderStatus status) { 
  5.     return Objects.equals(status, OrderStatus.FINISHED); 

 3.4.枚举的属性字段必须是私有不可变

枚举通常被当做常量使用,如果枚举中存在公共属性字段或设置字段方法,那么这些枚举常量的属性很容易被修改。理想情况下,枚举中的属性字段是私有的,并在私有构造函数中赋值,没有对应的 Setter 方法,最好加上 final 修饰符。

反例:

  1. public enum UserStatus { 
  2.     DISABLED(0, "禁用"), 
  3.     ENABLED(1, "启用"); 
  4.  
  5.     public int value; 
  6.     private String description; 
  7.  
  8.     private UserStatus(int value, String description) { 
  9.         this.value = value; 
  10.         this.description = description; 
  11.     } 
  12.  
  13.     public String getDescription() { 
  14.         return description; 
  15.     } 
  16.  
  17.     public void setDescription(String description) { 
  18.         this.description = description; 
  19.     } 

 正例:

  1. public enum UserStatus { 
  2.     DISABLED(0, "禁用"), 
  3.     ENABLED(1, "启用"); 
  4.  
  5.     private final int value; 
  6.     private final String description; 
  7.  
  8.     private UserStatus(int value, String description) { 
  9.         this.value = value; 
  10.         this.description = description; 
  11.     } 
  12.  
  13.     public int getValue() { 
  14.         return value; 
  15.     } 
  16.  
  17.     public String getDescription() { 
  18.         return description; 
  19.     } 

 3.5.小心 String.split(String regex)

字符串 String 的 split 方法,传入的分隔字符串是正则表达式!部分关键字(比如.[]()\|等)需要转义

反例:

  1. "a.ab.abc".split("."); // 结果为[] 
  2. "a|ab|abc".split("|"); // 结果为["a""|""a""b""|""a""b""c"

 正例:

  1. "a.ab.abc".split("\\."); // 结果为["a""ab""abc"
  2. "a|ab|abc".split("\\|"); // 结果为["a""ab""abc"

本文转载自网络,原文链接:https://www.toutiao.com/i6939753067793383972/

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • 这些提高你代码性能的技巧你值得拥有

    这些提高你代码性能的技巧你值得拥有

  • React 受控组件,Hooks 方式!

    React 受控组件,Hooks 方式!

  • Steam 增加了对 Mesa 着色器单文件缓存

    Steam 增加了对 Mesa 着色器单文件缓存

  • 教大家如何手写一个AQS?

    教大家如何手写一个AQS?

腾讯云代理商
海外云服务器