这个问题说明了一切。尽管命中率不是很高(我测量到它慢了1.5倍到2倍),但使用try-catch的字节码和不使用try-catch的字节码没有区别。那么是什么让它变得更慢呢?
Pl。请注意,问题不是抛出异常的开销,而是进入/离开try块的开销。
编辑:这是代码(在热点1.6.0_31服务器上运行)
static void tryCatch()
{
int i = 0;
long l1 = getTime();
for(int j = 0; j < 100000; j++)
{
try
{
i++;
}
catch(Exception e)
{
}
}
long l2 = getTime();
System.out.println("with try-catch: " + (l2 - l1) + ": " + i);
}
static void noTryCatch()
{
int i = 0;
long l1 = getTime();
for(int j = 0; j < 100000; j++)
{
i++;
}
long l2 = getTime();
System.out.println("w/o try-catch: " + (l2 - l1) + ": " + i);
}
static long getTime()
{
return System.nanoTime();
}
发布于 2012-04-16 15:19:39
由于您有一个微基准测试,因此您更有可能测试try/catch块对JVM编译器的混淆程度。例如,JVM可以足够智能地进行更改
for(int j = 0; j < 100000; j++) {
i++;
}
转到
i += 100000 * 1;
使用try/catch块可能会阻止更具侵略性的优化,但对于更实际的代码块可能没有任何影响。
在任何情况下,我通常会修改如下内容
for(int j = 0; j < 100000; j++) {
try {
// do something
} catch(Exception e) {
// break or return
}
}
。
try {
for(int j = 0; j < 100000; j++) {
// do something
}
} catch(Exception e) {
// continue or return
}
发布于 2013-09-22 06:13:36
对于另一个问题,我的microbenchmark显示使用/不使用try-catch块、是否在块中抛出异常没有显著差异。
https://stackoverflow.com/questions/10169671
复制相似问题