Java 优化编程阅读笔记二
第二章内存管理
这章看得不太懂,觉得书上还是没有说明原理,等看到其它的再补充上来吧。
第三章表达式、语句和保留字
使用循环语句的几个建议:
1. 当作数组拷贝操作时,采用System.arraycopy()效率更高。
使用了以下代码段:
| public class Test { public Test(){ } public static void main(String []args){ long startIndex,endIndex; int maxLength=1000000; int []a=new int[maxLength]; int []b=new int[maxLength]; for(int i=0;i<a.length;i++){ a[i]=i; } startIndex=System.currentTimeMillis(); for(int i=0;i<a.length;i++){ b[i]=a[i]; } endIndex=System.currentTimeMillis(); System.out.println(endIndex-startIndex); int []c=new int[maxLength]; startIndex=System.currentTimeMillis(); System.arraycopy(a, 0, c, 0, c.length); endIndex=System.currentTimeMillis(); System.out.println(endIndex-startIndex); } } |
发现结果如下:
| maxLength值 | 1000000 | 2500000 | 5000000 |
| 结果1 | 0 | 15 | 31 |
| 结果2 | 0 | 16 |
47 |
并非和文章中所提到的一样(2500000,105,45),所以不赞同作者的这个观点。
2. 尽量避免在循环体中调用方法
3. 最好避免在循环体内存取数据元素,比较好的办法是在循环体内采用临时变量,在循环体外更改数组的值。这是因为在循环体内使用变量比存取数组元素要快。
4. 避免在做最终条件时采用方法返回值的方式判断。
如:
...
while(isTrue()){
...
}
...
应该写作:
boolean isTrue=isTrue();
while(isTrue){
...
}
...
5. 尽量避免在循环体中使用try-catch 块,最好在循环体外使用。
如:
do{
try{
...
}catch(Exception e){
...
}
}while(isTrue);
建议使用下面的方式:
try{
do{
...
}while(isTrue);
}catch(Exception e){
...
}
6. 在多重循环中,如果有可能,尽量将最长的循环放在最内层,最短的循环放在最外层。

发表评论