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

2020-07-23 05:28发布

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

2条回答
来,给爷笑一个
2楼-- · 2020-07-23 05:30

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.

查看更多
够拽才男人
3楼-- · 2020-07-23 05:47

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
}
查看更多
登录 后发表回答