这个问题说明了一切。尽管命中不是很显着(我测量它慢了 1.5 倍到 2 倍),但带有 try-catch 的字节码和没有它的字节码之间没有区别。那么是什么让它通常变慢呢?
PL。请注意,问题不是关于抛出异常的开销,而是关于进入/离开 try 块的开销。
编辑:这是代码(在 Hotspot 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();
}