条件操作符更加的简捷
例子:
public class IF { public int method(boolean isDone) { if (isDone) { return 0; } else { return 10; } } } |
更正:
public class IF { public int method(boolean isDone) { return (isDone ? 0 : 10); } } |
十八、使用条件操作符代替"if (cond) a = b; else a = c;" 结构
例子:
public class IFAS { void method(boolean isTrue) { if (isTrue) { _value = 0; } else { _value = 1; } } private int _value = 0; } |
更正:
public class IFAS { void method(boolean isTrue) { _value = (isTrue ? 0 : 1); // compact expression. } private int _value = 0; } |
十九、不要在循环体中实例化变量
在循环体中实例化临时变量将会增加内存消耗
例子:
import java.util.Vector; public class LOOP { void method (Vector v) { for (int i=0;i < v.size();i++) { Object o = new Object(); o = v.elementAt(i); } } } |
更正:
在循环体外定义变量,并反复使用
import java.util.Vector; public class LOOP { void method (Vector v) { Object o; for (int i=0;i<v.size();i++) { o = v.elementAt(i); } } } |
二十、确定 StringBuffer的容量
StringBuffer的构造器会创建一个默认大小(通常是16)的字符数组。在使用中,如果超出这个大小,就会重新分配内存,创建一个更大的数组,并将原先的数组复制过来,再丢弃旧的数组。在大多数情况下,你可以在创建 StringBuffer的时候指定大小,这样就避免了在容量不够的时候自动增长,以提高性能。
例子:
public class RSBC { void method () { StringBuffer buffer = new StringBuffer(); // violation buffer.append ("hello"); } } |
更正:
为StringBuffer提供寝大小。
public class RSBC { void method () { StringBuffer buffer = new StringBuffer(MAX); buffer.append ("hello"); } private final int MAX = 100; } |
参考资料:
Dov Bulka, "Java Performance and Scalability Volume 1: Server-Side Programming Techniques" Addison Wesley, ISBN: 0-201-70429-3 p.30 – 31 |