Java: overhead of entering/using “try-catch” blocks?

匆匆过客 提交于 2020-02-27 08:35:31

问题


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. note that the question is not about overhead of throwing an exception, but of entering/leaving a try block.

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

回答1:


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++;
}

into

i += 100000 * 1;

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
}



回答2:


My microbenchmark for another question showed there is no significant difference between using/not using a try-catch block, with or without throwing exception in a block or not.



来源:https://stackoverflow.com/questions/10169671/java-overhead-of-entering-using-try-catch-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!