class="java" name="code">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
?
结论:?
?