What are the effects of exceptions on performance in Java?

前端 未结 17 2351
情深已故
情深已故 2020-11-22 01:21

Question: Is exception handling in Java actually slow?

Conventional wisdom, as well as a lot of Google results, says that exceptional logic shouldn\'t be used for n

17条回答
  •  盖世英雄少女心
    2020-11-22 01:44

    I changed @Mecki 's answer above to have method1 return a boolean and a check in the calling method, as you cannot just replace an Exception with nothing. After two runs, method1 was still either the fastest or as fast as method2.

    Here is snapshot of the code:

    // Calculates without exception
    public boolean method1(int i) {
        value = ((value + i) / i) << 1;
        // Will never be true
        return ((i & 0xFFFFFFF) == 1000000000);
    
    }
    ....
       for (i = 1; i < 100000000; i++) {
                if (t.method1(i)) {
                    System.out.println("Will never be true!");
                }
        }
    

    and results:

    Run 1

    method1 took 841 ms, result was 2
    method2 took 841 ms, result was 2
    method3 took 85058 ms, result was 2
    

    Run 2

    method1 took 821 ms, result was 2
    method2 took 838 ms, result was 2
    method3 took 85929 ms, result was 2
    

提交回复
热议问题