五種Java程式設計高效程式設計方法 - Babla

banq發表於2021-05-14

1. 移位操作可以大大提高效率。使用移位操作來計算樂觀整數2^n(n是樂觀整數)的乘除。

Inefficient code:
int num1 = a * 4; int num2 = a / 4;

Environment friendly code:
int num1 = a << 2; int num2 = a >> 2;

 
2. 類中每個欄位變數在每個物件中都有一個複製,而靜態固定的每個欄位則只有一個。

Inefficient code:
public class HttpConnection {
non-public remaining lengthy timeout = 5L;
...
}

Environment friendly code:
public class HttpConnection {
non-public static remaining lengthy TIMEOUT = 5L;
...
}

 

3.只要您直接分配資料值時,就只要建立一個物件引用直接賦值即可。

Inefficient code:
Lengthy i = new Lengthy(1L);
String s = new String("abc");

Environment friendly code:
Lengthy i = 1L;
String s = "abc";

 
4.在for迴圈的情況下使用方法呼叫會浪費資源。

Inefficient code:
Listing<UserDO> userList = ...;
for (int i = 0; i < userList.dimension(); i++) {
...
}

Environment friendly code:
Listing<UserDO> userList = ...;
int userLength = userList.dimension();
for (int i = 0; i < userLength; i++) {
...
}


5. 除非!至關重要,否則不要使用。在non-operator區域會再一次計算

Inefficient code:
if (!(a >= 10)) {
... // Your Code
} else {
... // Your Code
}

Environment friendly code:
if (a < 10) {
... // Your Code
} else {
... // Your Code
}

 

相關文章