自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何讓你的Java代碼性能"更高、更優(yōu)雅、遠(yuǎn)離BUG"?

開發(fā) 后端
代碼中的"壞味道",如"私欲"如"灰塵",每天都在增加,一日不去清除,便會越累越多。如果用功去清除這些"壞味道",不僅能提高自己的編碼水平,也能使代碼變得"精白無一毫不徹"。這里,整理了日常工作中的一些"壞味道",及清理方法,供大家參考

如何讓你的Java代碼性能\"更高、更優(yōu)雅、遠(yuǎn)離BUG\"?

前言

明代王陽明先生在《傳習(xí)錄》談為學(xué)之道時說:

私欲日生,如地上塵,一日不掃,便又有一層。著實(shí)用功,便見道無終窮,愈探愈深,必使精白無一毫不徹方可。

代碼中的"壞味道",如"私欲"如"灰塵",每天都在增加,一日不去清除,便會越累越多。如果用功去清除這些"壞味道",不僅能提高自己的編碼水平,也能使代碼變得"精白無一毫不徹"。這里,整理了日常工作中的一些"壞味道",及清理方法,供大家參考。

01 如何讓代碼性能更高?

1.1.需要 Map 的主鍵和取值時,應(yīng)該迭代 entrySet()

當(dāng)循環(huán)中只需要 Map 的主鍵時,迭代 keySet() 是正確的。但是,當(dāng)需要主鍵和取值時,迭代 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.應(yīng)該使用 Collection.isEmpty() 檢測空

使用 Collection.size() 來檢測空邏輯上沒有問題,但是使用 Collection.isEmpty() 使得代碼更易讀,并且可以獲得更好的性能。任何 Collection.isEmpty() 實(shí)現(xiàn)的時間復(fù)雜度都是 O(1) ,但是某些 Collection.size() 實(shí)現(xiàn)的時間復(fù)雜度可能是O(n)。

反例:

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

正例:

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

如果需要還需要檢測 null ,可采用 CollectionUtils.isEmpty(collection) 和CollectionUtils.isNotEmpty(collection)。

1.3.不要把集合對象傳給自己

將集合作為參數(shù)傳遞給集合自己的方法要么是一個錯誤,要么是無意義的代碼。

此外,由于某些方法要求參數(shù)在執(zhí)行期間保持不變,因此將集合傳遞給自身可能會導(dǎo)致異常行為。

反例:

  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()復(fù)制代碼 

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

java 的集合類用起來十分方便,但是看源碼可知,集合也是有大小限制的。每次擴(kuò)容的時間復(fù)雜度很有可能是 O(n) ,所以盡量指定可預(yù)知的集合大小,能減少集合的擴(kuò)容次數(shù)。

反例:

  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 會進(jìn)行優(yōu)化,但是在循環(huán)中字符串拼接,java 編譯期無法做到優(yōu)化,所以需要使用 StringBuilder 進(jìn)行替換。

反例:

  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編譯器會進(jìn)行優(yōu)化 
  5. StringBuilder sb = new StringBuilder(); 
  6. for (int i = 0; i < 10; i++) { 
  7.  sb.append(i); // 循環(huán)中,java編譯器無法進(jìn)行優(yōu)化,所以要手動使用StringBuilder 

1.6.List的隨機(jī)訪問

大家都知道數(shù)組和鏈表的區(qū)別:數(shù)組的隨機(jī)訪問效率更高。當(dāng)調(diào)用方法獲取到 List 后,如果想隨機(jī)訪問其中的數(shù)據(jù),并不知道該數(shù)組內(nèi)部實(shí)現(xiàn)是鏈表還是數(shù)組,怎么辦呢?可以判斷它是否實(shí)現(xiàn) RandomAccess 接口。

正例:

  1. // 調(diào)用別人的服務(wù)獲取到list 
  2. List<Integer> list = otherService.getList(); 
  3. if (list instanceof RandomAccess) { 
  4.  // 內(nèi)部數(shù)組實(shí)現(xiàn),可以隨機(jī)訪問 
  5.  System.out.println(list.get(list.size() - 1)); 
  6. else { 
  7.  // 內(nèi)部可能是鏈表實(shí)現(xiàn),隨機(jī)訪問效率低 

1.7.頻繁調(diào)用 Collection.contains 方法請使用 Set

在 java 集合類庫中,List 的 contains 方法普遍時間復(fù)雜度是 O(n) ,如果在代碼中需要頻繁調(diào)用 contains 方法查找數(shù)據(jù),可以先將 list 轉(zhuǎn)換成 HashSet 實(shí)現(xiàn),將 O(n) 的時間復(fù)雜度降為 O(1) 。

反例:

  1. ArrayList<Integer> list = otherService.getList(); 
  2. for (int i = 0; i <= Integer.MAX_VALUE; i++) { 
  3.  // 時間復(fù)雜度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.  // 時間復(fù)雜度O(1) 
  5.  set.contains(i); 

02 如何讓代碼更優(yōu)雅?

2.1.長整型常量后添加大寫 L

在使用長整型常量值時,后面需要添加 L ,必須是大寫的 L ,不能是小寫的 l ,小寫 l 容易跟數(shù)字 1 混淆而造成誤解。

反例:

  1. long value = l; 
  2. long max = Math.max(L, 5);復(fù)制代碼 

正例:

  1. long value = L; 
  2. long max = Math.max(L, L);復(fù)制代碼 

2.2.不要使用魔法值

當(dāng)你編寫一段代碼時,使用魔法值可能看起來很明確,但在調(diào)試時它們卻不顯得那么明確了。這就是為什么需要把魔法值定義為可讀取常量的原因。但是,-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.不要使用集合實(shí)現(xiàn)來賦值靜態(tài)成員變量

對于集合類型的靜態(tài)成員變量,不要使用集合實(shí)現(xiàn)來賦值,應(yīng)該使用靜態(tài)代碼塊賦值。

反例:

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

正例:

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

2.4.建議使用 try-with-resources 語句

Java 7 中引入了 try-with-resources 語句,該語句能保證將相關(guān)資源關(guān)閉,優(yōu)于原來的 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.刪除未使用的私有方法和字段

刪除未使用的私有方法和字段,使代碼更簡潔更易維護(hù)。若有需要再使用,可以從歷史提交中找回。

反例:

  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.刪除未使用的局部變量

刪除未使用的局部變量,使代碼更簡潔更易維護(hù)。

反例:

  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.刪除未使用的方法參數(shù)

未使用的方法參數(shù)具有誤導(dǎo)性,刪除未使用的方法參數(shù),使代碼更簡潔更易維護(hù)。但是,由于重寫方法是基于父類或接口的方法定義,即便有未使用的方法參數(shù),也是不能刪除的。

反例:

  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.刪除表達(dá)式的多余括號

對應(yīng)表達(dá)式中的多余括號,有人認(rèn)為有助于代碼閱讀,也有人認(rèn)為完全沒有必要。對于一個熟悉 Java 語法的人來說,表達(dá)式中的多余括號反而會讓代碼顯得更繁瑣。

反例:

  1. return (x); 
  2. return (x + 2); 
  3. int x = (y * 3) + 1; 
  4. int m = (n * 4 + 2);復(fù)制代碼 

正例:

  1. return x; 
  2. return x + 2; 
  3. int x = y * 3 + 1; 
  4. int m = n * 4 + 2;復(fù)制代碼 

2.9.工具類應(yīng)該屏蔽構(gòu)造函數(shù)

工具類是一堆靜態(tài)字段和函數(shù)的集合,不應(yīng)該被實(shí)例化。但是, Java 為每個沒有明確定義構(gòu)造函數(shù)的類添加了一個隱式公有構(gòu)造函數(shù)。所以,為了避免 java "小白"使用有誤,應(yīng)該顯式定義私有構(gòu)造函數(shù)來屏蔽這個隱式公有構(gòu)造函數(shù)。

反例:

  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語句捕獲異常后,什么也不進(jìn)行處理,就讓異常重新拋出,這跟不捕獲異常的效果一樣,可以刪除這塊代碼或添加別的處理。

反例:

  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.公有靜態(tài)常量應(yīng)該通過類訪問

雖然通過類的實(shí)例訪問公有靜態(tài)常量是允許的,但是容易讓人它誤認(rèn)為每個類的實(shí)例都有一個公有靜態(tài)常量。所以,公有靜態(tài)常量應(yīng)該直接通過類訪問。

反例:

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

正例:

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

2.12.不要用 NullPointerException 判斷空

空指針異常應(yīng)該用代碼規(guī)避(比如檢測不為空),而不是用捕獲異常的方式處理。

反例:

  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

當(dāng)要把其它對象或類型轉(zhuǎn)化為字符串時,使用 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 注解

當(dāng)一段代碼過時,但為了兼容又無法直接刪除,不希望以后有人再使用它時,可以添加 @Deprecated 注解進(jìn)行標(biāo)記。在文檔注釋中添加 @deprecated 來進(jìn)行解釋,并提供可替代方案

正例:

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

03 如何讓代碼遠(yuǎn)離 bug

3.1.禁止使用構(gòu)造方法 BigDecimal(double)

BigDecimal(double) 存在精度損失風(fēng)險,在精確計(jì)算或值比較的場景中可能會導(dǎo)致業(yè)務(wù)邏輯異常。

反例:

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

正例:

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

3.2.返回空數(shù)組和空集合而不是 null

返回 null ,需要調(diào)用方強(qiáng)制檢測 null ,否則就會拋出空指針異常。返回空數(shù)組或空集合,有效地避免了調(diào)用方因?yàn)槲礄z測 null 而拋出空指針異常,還可以刪除調(diào)用方檢測 null 的語句使代碼更簡潔。

反例:

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

正例:

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

3.3.優(yōu)先使用常量或確定值來調(diào)用 equals 方法

對象的 equals 方法容易拋空指針異常,應(yīng)使用常量或確定有值的對象來調(diào)用 equals 方法。當(dāng)然,使用java.util.Objects.equals() 方法是最佳實(shí)踐。

反例:

  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. public void isFinished(OrderStatus status) { 
  4.  return Objects.equals(status, OrderStatus.FINISHED); 

3.4.枚舉的屬性字段必須是私有不可變

枚舉通常被當(dāng)做常量使用,如果枚舉中存在公共屬性字段或設(shè)置字段方法,那么這些枚舉常量的屬性很容易被修改。理想情況下,枚舉中的屬性字段是私有的,并在私有構(gòu)造函數(shù)中賦值,沒有對應(yīng)的 Setter 方法,最好加上 final 修飾符。

反例:

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

正例:

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

3.5.小心 String.split(String regex)

字符串 String 的 split 方法,傳入的分隔字符串是正則表達(dá)式!部分關(guān)鍵字(比如.[]()|等)需要轉(zhuǎn)義

反例:

  1. "a.ab.abc".split("."); // 結(jié)果為[] 
  2. "a|ab|abc".split("|"); // 結(jié)果為["a""|""a""b""|""a""b""c"

正例:

  1. "a.ab.abc".split("."); // 結(jié)果為[] 
  2. "a|ab|abc".split("|"); // 結(jié)果為["a""|""a""b""|""a""b""c"

04 總結(jié)

這篇文章,可以說是從事 Java 開發(fā)的經(jīng)驗(yàn)總結(jié),分享出來以供大家參考。希望能幫大家避免踩坑,讓代碼更加高效優(yōu)雅。

 

責(zé)任編輯:龐桂玉 來源: 今日頭條
相關(guān)推薦

2022-03-08 06:41:35

css代碼

2020-04-03 14:55:39

Python 代碼編程

2024-05-24 10:51:51

框架Java

2022-04-10 10:41:17

ESLint異步代碼

2023-11-23 13:50:00

Python代碼

2024-01-12 09:35:30

Java代碼開發(fā)

2018-07-12 14:20:33

SQLSQL查詢編寫

2022-03-11 12:14:43

CSS代碼前端

2022-12-26 07:47:37

JDK8函數(shù)式接口

2025-02-10 00:25:00

命令模式擴(kuò)展機(jī)制系統(tǒng)

2023-07-10 09:39:02

lambdaPython語言

2025-04-21 17:55:25

2022-11-18 08:32:23

spring參數(shù)解析器

2017-09-27 16:09:29

代碼

2023-12-21 10:26:30

??Prettier

2022-05-13 08:48:50

React組件TypeScrip

2021-12-07 08:16:34

React 前端 組件

2024-07-03 08:13:56

規(guī)則執(zhí)行器代碼

2024-07-30 14:09:19

裝飾器Python代碼

2019-11-25 10:20:54

CSS代碼javascript
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號