Java:输入/使用“try-catch”的开销块? [英] Java: overhead of entering/using "try-catch" blocks?

查看:169
本文介绍了Java:输入/使用“try-catch”的开销块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题说明了一切。虽然命中率不是很高(我测量它的速度在1.5x到2x之间),但是try-catch的字节代码与没有try-catch的字节代码之间没有区别。那么是什么让它通常变慢?

The question says it all. Although the hit is not highly significant (I measured it to be between 1.5x to 2x slower), there's no difference between the byte code with try-catch and the byte code without it. So what makes it generally slower?

Pl。请注意,问题不是抛出异常的开销,而是进入/离开try块。

Pl. note that the question is not about overhead of throwing an exception, but of entering/leaving a try block.

编辑:
这里是代码(在Hotspot上运行) 1.6.0_31服务器)

here's the code (run on Hotspot 1.6.0_31 server)

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();       
}

EDIT2:发现这个实际执行此类测试的好链接: http://jsperf.com/try-catch-overhead

found this nice link for actually performing such tests: http://jsperf.com/try-catch-overhead

推荐答案

由于您有一个微基准测试,因此您更有可能测试try / catch块与JVM编译器的混淆程度。例如,JVM可以足够聪明地更改

Since you have a micro-benchmark its is more likely you are testing how confusing the try/catch block is to the JVM compiler. For example, the JVM can be smart enough to change

for(int j = 0; j < 100000; j++) {
    i++;
}

进入

i += 100000 * 1;

可能会阻止更具侵略性的优化,但对于a可能没有任何区别更实际的代码块。

using the try/catch block may prevent the more aggresive optimisations, but might not make any difference for a more realistic block of code.

在任何情况下我都会改变类似

In any case I would normally change something like

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
}

这篇关于Java:输入/使用“try-catch”的开销块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆