TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
通过代码测试发现,try catch放在循环内的性能表现高于放在循环外,而我一直以为try catch放在循环外的性能要高于放在循环内。而且通过不同版本JDK测试,发现JDK7比JDK6的优化更好,但若不使用try catch,JDK6的表现要稍微高于JDK7。这里希望和大家一起探讨下。
下面是我的测试代码,分别使用了JDK 1.6.0_34 x64和 JDK 1.7.0_09 x64两个版本,测试时启用了server模式,运行命令均为:
java -server -cp .; com.test.Main
测试环境:
OS: win7 旗舰版 x64
CPU: 2.0G(i7二代)
内存:20G(DDR3 1600)
public static void main(String[] args)
{
Main ins = new Main();
int size = 10000000;
ins.method1(size);
ins.method2(size);
ins.method3(size);
}
public void method1(int size)
{
long start = System.currentTimeMillis();
ArrayList<String> al = new ArrayList<String>();
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<String> al = new ArrayList<String>();
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));
}
public void method3(int size)
{
long start = System.currentTimeMillis();
ArrayList<String> al = new ArrayList<String>();
String str = null;
for (int i = 0; i < size; i++)
{
str = "str" + i;
al.add(str);
}
System.out.println("method3 total: " + (System.currentTimeMillis() - start));
}
[/code]
测试结果为:
JDK7:
method1 total: 9846 【放在循环外】
method2 total: 1266 【放在循环内】
method3 total: 1523 【不使用try catch】
JDK6:
method1 total: 3457 【放在循环外】
method2 total: 3280 【放在循环内】
method3 total: 1323 【不使用try catch】 |
|