将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

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2008 powered by YuLog