try catch放在循环内还是放在循环外的性能对比.

 通过代码测试发现,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】

个人觉得放外面放里面需要根据业务来决定.
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值