天天看點

如何優化 Java 代碼

讓代碼性能更高

需要 Map 的主鍵和取值時,應該疊代 entrySet()

當循環中隻需要 Map 的主鍵時,疊代 keySet() 是正确的。但是,當需要主鍵和取值時,疊代 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();

    ...

}

應該使用Collection.isEmpty()檢測空

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

反例:

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

    ...

}

正例:

if (collection.isEmpty()) {

    ...

}

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

不要把集合對象傳給自己

此外,由于某些方法要求參數在執行期間保持不變,是以将集合傳遞給自身可能會導緻異常行為。

反例:

List<String> list = new ArrayList<>();

list.add("Hello");

list.add("World");

if (list.containsAll(list)) { // 無意義,總是傳回true

    ...

}

list.removeAll(list); // 性能差, 直接使用clear()

集合初始化盡量指定大小

Java 的集合類用起來十分友善,但是看源碼可知,集合也是有大小限制的。每次擴容的時間複雜度很有可能是 O(n) ,是以盡量指定可預知的集合大小,能減少集合的擴容次數。

反例:

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);

}

字元串拼接使用 StringBuilder 

一般的字元串拼接在編譯期 Java 會進行優化,但是在循環中字元串拼接, Java 編譯期無法做到優化,是以需要使用 StringBuilder 進行替換。

反例:

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; // 沒問題,java編譯器會進行優化

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 10; i++) {

    sb.append(i);  // 循環中,java編譯器無法進行優化,是以要手動使用StringBuilder

}

List 的随機通路

大家都知道數組和連結清單的差別:數組的随機通路效率更高。當調用方法擷取到 List 後,如果想随機通路其中的資料,并不知道該數組内部實作是連結清單還是數組,怎麼辦呢?可以判斷它是否實作* RandomAccess *接口。

正例:

// 調用别人的服務擷取到list

List<Integer> list = otherService.getList();

if (list instanceof RandomAccess) {

    // 内部數組實作,可以随機通路

    System.out.println(list.get(list.size() - 1));

} else {

    // 内部可能是連結清單實作,随機通路效率低

}

頻繁調用 Collection.contains 方法請使用 Set

在 Java 集合類庫中,List 的 contains 方法普遍時間複雜度是 O(n) ,如果在代碼中需要頻繁調用 contains 方法查找資料,可以先将 list 轉換成 HashSet 實作,将 O(n) 的時間複雜度降為 O(1) 。

反例: 

ArrayList<Integer> list = otherService.getList();

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

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

反例:

long value = 1l;

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

正例:

long value = 1L;

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

不要使用魔法值

當你編寫一段代碼時,使用魔法值可能看起來很明确,但在調試時它們卻不顯得那麼明确了。這就是為什麼需要把魔法值定義為可讀取常量的原因。但是,-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) {

    ...

}

不要使用集合實作來指派靜态成員變量

對于集合類型的靜态成員變量,不要使用集合實作來指派,應該使用靜态代碼塊指派。

反例:

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");

};

建議使用 try-with-resources 語句

Java 7 中引入了 try-with-resources 語句,該語句能保證将相關資源關閉,優于原來的 try-catch-finally 語句,并且使程式代碼更安全更簡潔。

反例:

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

        ...

    }

}

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

删除未使用的私有方法和字段,使代碼更簡潔更易維護。若有需要再使用,可以從曆史送出中找回。

反例: 

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;

    }

}

删除未使用的局部變量

删除未使用的局部變量,使代碼更簡潔更易維護。

反例:

public int sum(int a, int b) {

    int c = 100;

    return a + b;

}

正例:

public int sum(int a, int b) {

    return a + b;

}

删除未使用的方法參數

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

反例:

public int sum(int a, int b, int c) {

    return a + b;

}

正例:

public int sum(int a, int b) {

    return a + b;

}

删除表達式的多餘括号

對應表達式中的多餘括号,有人認為有助于代碼閱讀,也有人認為完全沒有必要。對于一個熟悉 Java 文法的人來說,表達式中的多餘括号反而會讓代碼顯得更繁瑣。

反例:

return (x);

return (x + 2);

int x = (y * 3) + 1;

int m = (n * 4 + 2);

正例:

return x;

return x + 2;

int x = y * 3 + 1;

int m = n * 4 + 2;

工具類應該屏蔽構造函數

工具類是一堆靜态字段和函數的集合,不應該被執行個體化。但是,Java 為每個沒有明确定義構造函數的類添加了一個隐式公有構造函數。是以,為了避免 java "小白"使用有誤,應該顯式定義私有構造函數來屏蔽這個隐式公有構造函數。

反例: 

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;

    }

}

删除多餘的異常捕獲并抛出

用 catch 語句捕獲異常後,什麼也不進行處理,就讓異常重新抛出,這跟不捕獲異常的效果一樣,可以删除這塊代碼或添加别的處理。

反例:

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();

    }

}

公有靜态常量應該通過類通路

雖然通過類的執行個體通路公有靜态常量是允許的,但是容易讓人它誤認為每個類的執行個體都有一個公有靜态常量。是以,公有靜态常量應該直接通過類通路。

反例:

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;

不要用NullPointerException判斷空

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

反例:

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();

}

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

當要把其它對象或類型轉化為字元串時,使用 String.valueOf(value) 比""+value 的效率更高。

反例:

int i = 1;

String s = "" + i;

正例:

int i = 1;

String s = String.valueOf(i);

過時代碼添加 @Deprecated 注解

當一段代碼過時,但為了相容又無法直接删除,不希望以後有人再使用它時,可以添加 @Deprecated 注解進行标記。在文檔注釋中添加 @deprecated 來進行解釋,并提供可替代方案

正例:

@Deprecated

public void save(){

    // do something

}

讓代碼遠離 Bug

禁止使用構造方法 BigDecimal(double)

BigDecimal(double) 存在精度損失風險,在精确計算或值比較的場景中可能會導緻業務邏輯異常。

反例:

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

正例:

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

傳回空數組和空集合而不是 null

傳回 null ,需要調用方強制檢測 null ,否則就會抛出空指針異常。傳回空數組或空集合,有效地避免了調用方因為未檢測 null 而抛出空指針異常,還可以删除調用方檢測 null 的語句使代碼更簡潔。

反例:

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

        ...

    }

}

優先使用常量或确定值來調用 equals 方法

對象的 equals 方法容易抛空指針異常,應使用常量或确定有值的對象來調用 equals 方法。當然,使用 java.util.Objects.equals() 方法是最佳實踐。

反例:

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);

}

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

枚舉通常被當做常量使用,如果枚舉中存在公共屬性字段或設定字段方法,那麼這些枚舉常量的屬性很容易被修改。理想情況下,枚舉中的屬性字段是私有的,并在私有構造函數中指派,沒有對應的 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;

    }

}

小心String.split(String regex)

字元串 String 的 split 方法,傳入的分隔字元串是正規表達式!部分關鍵字(比如.[]()\| 等)需要轉義

反例:

"a.ab.abc".split("."); // 結果為[]

"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 開發的經驗總結,分享出來以供大家參考。希望能幫大家避免踩坑,讓代碼更加高效優雅。

————————————————

版權聲明:本文為CSDN部落客「CSDN資訊」的原創文章,遵循 CC 4.0 BY-SA 版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/csdnnews/article/details/100987866

繼續閱讀