使用异常处理正常的代码流很糟糕 - 速度很慢,代码质量很差,从第1天起,我们都会把这种情况带入我们的头脑中。至少我有!这也是有道理的,异常每次调用时都会生成堆栈跟踪,堆栈跟踪需要很长时间才能生成,因此抛出和捕获的异常比等效的if语句慢得多。Java中异常的速度
所以我决定做一个快速的例子来证明这一点。
public static void main(String[] args) throws Exception {
Object[] objs = new Object[500000];
for (int i = 0; i < objs.length; i++) {
if (Math.random() < 0.5) {
objs[i] = new Object();
}
}
long cur = System.currentTimeMillis();
for (Object o : objs) {
try {
System.out.print(o.getClass());
}
catch (Exception e) {
System.out.print("null");
}
}
System.err.println("Try/catch: "+(System.currentTimeMillis() - cur));
cur = System.currentTimeMillis();
for (Object o : objs) {
if(o==null) {
System.out.print("null");
}
else {
System.out.print(o.getClass());
}
}
System.err.println("If: "+(System.currentTimeMillis() - cur));
}
然而,上运行的代码,我吃惊地看到以下内容:
Try/catch: 11204
If: 11953
我再次运行代码,此时 “如果” 是快:
Try/catch: 12188
If: 12187
。 ..但只有一个毫秒。
这是所有在服务器虚拟机上运行的,我知道大部分时间都会被print()
语句占用,有些运行会显示速度比try/catch快。但无论如何,他们当然不应该接近?那么如何生成堆栈跟踪比单个if语句更快呢?
编辑:为了澄清,这个问题是一个纯粹的学术 - 我知道使用正常代码流的异常是很好,绝对不会这样做!
谢谢,该通讯解释得相当好。我以前看过它,但没有那篇文章! – berry120 2011-01-30 00:26:06