将try catch 区段置于循环之外
try/catch位于循环内会对性能造成影响,下面测试代码中两个方法只是try/catch的位置不同,结果就会有较大差异
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
Test test = new Test();
int size = 1000;
test.method1(size);
test.method2(size);
}
public void method1(int size){
long start = System.currentTimeMillis();
ArrayList al = new ArrayList();
String str = null;
try{
for(int i=0; i<size; i++){
str = "str" + i;
al.add(str);
}
}catch(Exception e){
}
System.out.println("method1 total: " +
(System.currentTimeMillis() - start));
}
public void method2(int size){
long start = System.currentTimeMillis();
ArrayList al = new ArrayList();
String str = null;
for(int i=0; i<size; i++){
try{
str = "str" + i;
al.add(str);
}catch(Exception e){
}
}
System.out.println("method2 total: " +
(System.currentTimeMillis() - start));
}
}
我机器上的结果:
method1 total: 0
method2 total: 15
irini
2007-05-13 21:18:05
评论:0
阅读:91
引用:0
