日期:2014-05-20  浏览次数:20688 次

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;