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