使用移位操作來代替'a / b'操作 和 'a * b'操作
"/"是一個很“昂貴”的操作,使用移位操作將會更快更有效。
例子:
public class SDIV {
public static final int NUM = 16;
public void calculate(int a) {
int div = a / 4; // should be replaced with "a >> 2".
int div2 = a / 8; // should be replaced with "a >> 3".
int temp = a / 3;
}
}
更正:
public class SDIV {
public static final int NUM = 16;
public void calculate(int a) {
int div = a >> 2;
int div2 = a >> 3;
int temp = a / 3; // 不能轉換成位移操作
}
}
不要總是使用取反操作符(!)
取反操作符(!)降低程序的可讀性,所以不要總是使用。
例子:
public class DUN {
boolean method (boolean a, boolean b) {
if (!a)
return !a;
else
return !b;
}
}
更正:
如果可能不要使用取反操作符(!)