八、如果只是查找单个字符的话,用charAt()代替startsWith()
用一个字符作为参数调用startsWith()也会工作的很好,但从性能角度上来看,调用用String API无疑是错误的!
例子:
public class PCTS {
private void method(String s) {
if (s.startsWith("a")) { // violation
// ...
}
}
}
更正
将'startsWith()' 替换成'charAt()'.
public class PCTS {
private void method(String s) {
if ('a' == s.charAt(0)) {
// ...
}
}
}
参考资料:
Dov Bulka, "Java Performance and Scalability Volume 1: Server-Side Programming
Techniques" Addison Wesley, ISBN: 0-201-70429-3
九、使用移位操作来代替'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; // 不能转换成位移操作
}
}
十、使用移位操作代替'a * b'
同上。
_但我个人认为,除非是在一个非常大的循环内,性能非常重要,而且你很清楚你自己在做什么,方可使用这种方法。否则提高性能所带来的程序晚读性的降低将是不合算的。_
例子:
public class SMUL {
public void calculate(int a) {
int mul = a * 4; // should be replaced with "a << 2".
int mul2 = 8 * a; // should be replaced with "a << 3".
int temp = a * 3;
}
}
更正:
package OPT;
public class SMUL {
public void calculate(int a) {
int mul = a << 2;
int mul2 = a << 3;
int temp = a * 3; // 不能转换
}
}