JDK6和JDK7对try catch的性能优化问题
http://www.iteye.com/topic/1127950
我通过代码测试发现,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));
}
JDK7:
method1 total: 9846 【放在循环外】
method2 total: 1266 【放在循环内】
method3 total: 1523 【不使用try catch】
JDK6:
method1 total: 3457 【放在循环外】
method2 total: 3280 【放在循环内】
method3 total: 1323 【不使用try catch】
[最优解释]
必须提示你的测试不准确。
①、测试过程中你用到了ArrayList,并且没有指定空间,ArrayList会依据权值自动增长,jdk6和jdk7权值计算是一样的吗?
②、64位系统和32位系统的内存分页是完全不一样的,这和java没有关系,将10000000个字符串存入内存必定导致大量分页,而jdk6在32位系统上比64位更加稳定和高效。
③、如果不考虑空间复杂度的话,计算机只会做加法,所以将写内存转为加法计算测试的性能应该更准确。
[其他解释]
嗯,有道理,循环操作换成整数累加后,jdk6和jdk7的性能表现就是一样的了,而且try catch放到循环外的性能要比放到循环内的性能好很多。非常感谢bree66的回答