JAVA之Exception篇(2)——性能

通过Java代码测试了创建普通对象、异常对象及抛出并捕获异常的性能开销,结果显示创建异常对象的时间远高于普通对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看一段java代码:

public class Performance {

	private int testTimes;

	public Performance(int testTimes) {
		this.testTimes = testTimes;
	}

	public long newObject() {
		long l = System.nanoTime();
		for (int i = 0; i < testTimes; i++) {
			new Object();
		}
		long time = (System.nanoTime() - l);
		System.out.println("建立对象:" + time);
		return time;
	}

	public long newException() {
		long l = System.nanoTime();
		for (int i = 0; i < testTimes; i++) {
			new Exception();
		}
		long time = (System.nanoTime() - l);
		System.out.println("建立异常对象:" + time);
		return time;
	}

	public long newSubException() {
		long l = System.nanoTime();
		for (int i = 0; i < testTimes; i++) {
			new NullPointerException();
		}
		long time = (System.nanoTime() - l);
		System.out.println("\n建立NullPointerException异常的子类对象:" + time);
		return time;
	}

	public long catchException() {
		long l = System.nanoTime();
		for (int i = 0; i < testTimes; i++) {
			try {
				throw new Exception();
			} catch (Exception e) {
			}
		}
		long time = (System.nanoTime() - l);
		System.out.println("建立、抛出并接住异常对象:" + time);
		return time;
	}

	public static void main(String[] args) {
		Performance test = new Performance(100000);
		long objTime = test.newObject();
		long excTime = test.newException();
		long catchTime = test.catchException();
		
		
		long throwTime = catchTime - excTime;
		System.out.println("抛出并接住异常对象:" + throwTime);
		System.out.println("\n建立异常对象所用时间是建立对象的" + excTime / objTime + "倍");		
		
		long subTime = test.newSubException();
		System.out.println("建立Exception对象所用时间是建立子类异常NullPointerException对象的" + (excTime/subTime));
	}
}

 

输出结果:

建立对象:7394974
建立异常对象:206183309
建立、抛出并接住异常对象:249589489
抛出并接住异常对象:43406180

建立异常对象所用时间是建立对象的27倍

建立NullPointerException异常的子类对象:206053708
建立Exception对象所用时间是建立子类异常NullPointerException对象的1

 

结论:
  1. 建立异常对象花费的时间比建立非异常对象要多得多,所以非异常情况不要使用异常。(由于是为异常情况设计的,所以JVM没有考虑性能问题)
  2. 抛出Exception异常跟抛出其子类异常成本一样,只是如果抛出顶层类Exception,调用方无法清楚知道错误在哪里,所以建议不要直接抛出或接住Exception类。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值