溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么使Java代碼性能變得更高

發(fā)布時(shí)間:2021-12-31 15:52:47 來(lái)源:億速云 閱讀:120 作者:iii 欄目:編程語(yǔ)言

本篇內(nèi)容介紹了“怎么使Java代碼性能變得更高”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

01 如何讓代碼性能更高?

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

當(dāng)循環(huán)中只需要 Map 的主鍵時(shí),迭代 keySet() 是正確的。但是,當(dāng)需要主鍵和取值時(shí),迭代 entrySet() 才是更高效的做法,比先迭代 keySet() 后再去 get 取值性能更佳。

反例:

Map<String, String> map = ...; for (String key : map.keySet()) {  String value = map.get(key);  ... }

正例:

Map<String, String> map = ...; for (Map.Entry<String, String> entry : map.entrySet()) {  String key = entry.getKey();  String value = entry.getValue();  ... }

1.2.應(yīng)該使用 Collection.isEmpty() 檢測(cè)空

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

反例:

if (collection.size() == 0) {  ... }

正例:

if (collection.isEmpty()) {  ... }

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

1.3.不要把集合對(duì)象傳給自己

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

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

反例:

List<String> list = new ArrayList<>(); list.add("Hello"); list.add("World"); if (list.containsAll(list)) { // 無(wú)意義,總是返回true  ... } list.removeAll(list); // 性能差, 直接使用clear()復(fù)制代碼

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

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

反例:

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

正例:

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

1.5.字符串拼接使用 StringBuilder

一般的字符串拼接在編譯期 java 會(huì)進(jìn)行優(yōu)化,但是在循環(huán)中字符串拼接,java 編譯期無(wú)法做到優(yōu)化,所以需要使用 StringBuilder 進(jìn)行替換。

反例:

String s = ""; for (int i = 0; i < 10; i++) {  s += i; }

正例:

String a = "a"; String b = "b"; String c = "c"; String s = a + b + c; // 沒(méi)問(wèn)題,java編譯器會(huì)進(jìn)行優(yōu)化 StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) {  sb.append(i); // 循環(huán)中,java編譯器無(wú)法進(jìn)行優(yōu)化,所以要手動(dòng)使用StringBuilder }

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

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

正例:

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

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

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

反例:

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

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

2.1.長(zhǎng)整型常量后添加大寫 L

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

反例:

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

正例:

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

2.2.不要使用魔法值

當(dāng)你編寫一段代碼時(shí),使用魔法值可能看起來(lái)很明確,但在調(diào)試時(shí)它們卻不顯得那么明確了。這就是為什么需要把魔法值定義為可讀取常量的原因。但是,-1、0 和 1 不被視為魔法值。

反例:

for (int i = 0; i < 100; i++){  ... } if (a == 100) {  ... }

正例:

private static final int MAX_COUNT = 100; for (int i = 0; i < MAX_COUNT; i++){  ... } if (count == MAX_COUNT) {  ... }

2.3.不要使用集合實(shí)現(xiàn)來(lái)賦值靜態(tài)成員變量

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

反例:

private static Map<String, Integer> map = new HashMap<String, Integer>() {  {  put("a", 1);  put("b", 2);  } }; private static List<String> list = new ArrayList<String>() {  {  add("a");  add("b");  } };

正例:

private static Map<String, Integer> map = new HashMap<>(); static {  map.put("a", 1);  map.put("b", 2); }; private static List<String> list = new ArrayList<>(); static {  list.add("a");  list.add("b"); };

2.4.建議使用 try-with-resources 語(yǔ)句

Java 7 中引入了 try-with-resources 語(yǔ)句,該語(yǔ)句能保證將相關(guān)資源關(guān)閉,優(yōu)于原來(lái)的 try-catch-finally 語(yǔ)句,并且使程序代碼更安全更簡(jiǎn)潔。

反例:

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) {  ...  }  }  } }

正例:

private void handle(String fileName) {  try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {  String line;  while ((line = reader.readLine()) != null) {  ...  }  } catch (Exception e) {  ...  } }

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

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

反例:

public class DoubleDemo1 {  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;  } }

2.6.刪除未使用的局部變量

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

反例:

public int sum(int a, int b) {  int c = 100;  return a + b; }

正例:

public int sum(int a, int b) {  return a + b; }

2.7.刪除未使用的方法參數(shù)

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

反例:

public int sum(int a, int b, int c) {  return a + b; }

正例:

public int sum(int a, int b) {  return a + b; }

2.8.刪除表達(dá)式的多余括號(hào)

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

反例:

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

正例:

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

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

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

反例:

public class MathUtils {  public static final double PI = 3.1415926D;  public static int sum(int a, int b) {  return a + b;  } }

正例:

public class MathUtils {  public static final double PI = 3.1415926D;  private MathUtils() {}  public static int sum(int a, int b) {  return a + b;  } }

2.10.刪除多余的異常捕獲并拋出

用catch語(yǔ)句捕獲異常后,什么也不進(jìn)行處理,就讓異常重新拋出,這跟不捕獲異常的效果一樣,可以刪除這塊代碼或添加別的處理。

反例:

private static String readFile(String fileName) throws IOException {  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;  } }

正例:

private static String readFile(String fileName) throws IOException {  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();  } }

2.11.公有靜態(tài)常量應(yīng)該通過(guò)類訪問(wèn)

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

反例:

public class User {  public static final String CONST_NAME = "name";  ... } User user = new User(); String nameKey = user.CONST_NAME;

正例:

public class User {  public static final String CONST_NAME = "name";  ... } String nameKey = User.CONST_NAME;

2.12.不要用 NullPointerException 判斷空

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

反例:

public String getUserName(User user) {  try {  return user.getName();  } catch (NullPointerException e) {  return null;  } }

正例:

public String getUserName(User user) {  if (Objects.isNull(user)) {  return null;  }  return user.getName(); }

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

當(dāng)要把其它對(duì)象或類型轉(zhuǎn)化為字符串時(shí),使用 String.valueOf(value) 比 ""+value 的效率更高。

反例:

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

正例:

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

2.14.過(guò)時(shí)代碼添加 @Deprecated 注解

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

正例:

/**  * 保存  *  * @deprecated 此方法效率較低,請(qǐng)使用{@link newSave()}方法替換它  */ @Deprecated public void save(){  // do something }

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

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

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

反例:

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

正例:

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

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

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

反例:

public static Result[] getResults() {  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) {  ...  }  } }

正例:

public static Result[] getResults() {  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) {  ...  } }

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

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

反例:

public void isFinished(OrderStatus status) {  return status.equals(OrderStatus.FINISHED); // 可能拋空指針異常 }

正例:

public void isFinished(OrderStatus status) {  return OrderStatus.FINISHED.equals(status); } public void isFinished(OrderStatus status) {  return Objects.equals(status, OrderStatus.FINISHED); }

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

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

反例:

public enum UserStatus {  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;  } }

正例:

public enum UserStatus {  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;  } }

3.5.小心 String.split(String regex)

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

反例:

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

正例:

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

“怎么使Java代碼性能變得更高”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI