Which is faster, try catch or if-else in java (WRT performance)

前端 未结 12 1934
暖寄归人
暖寄归人 2020-12-05 02:22

Which one is faster:

Either this

try {
  n.foo();
} 
catch(NullPointerException ex) {
}

or

if (n != null) n.foo();         


        
12条回答
  •  离开以前
    2020-12-05 02:37

    The answer to this is not as simple as it looks, because this will depend on the percentage of times that the object is really null. When this is very uncommon (say in 0.1% of the time), it might even be faster. To test this I've done some benchmarking with the following results (with Java 1.6 client):

    Benchmaring with factor 1.0E-4
    Average time of NullIfTest: 0.44 seconds
    Average time of NullExceptionTest: 0.45 seconds
    Benchmaring with factor 0.0010
    Average time of NullIfTest: 0.44 seconds
    Average time of NullExceptionTest: 0.46 seconds
    Benchmaring with factor 0.01
    Average time of NullIfTest: 0.42 seconds
    Average time of NullExceptionTest: 0.52 seconds
    Benchmaring with factor 0.1
    Average time of NullIfTest: 0.41 seconds
    Average time of NullExceptionTest: 1.30 seconds
    Benchmaring with factor 0.9
    Average time of NullIfTest: 0.07 seconds
    Average time of NullExceptionTest: 7.48 seconds
    

    This seems pretty conclusive to me. NPE's are just very slow. (I can post the benchmarking code if wanted)

    edit: I've just made an interesting discovery: when benchmarking using the server JVM, the results change drastically:

    Benchmaring with factor 1.0E-4
    Average time of NullIfTest: 0.33 seconds
    Average time of NullExceptionTest: 0.33 seconds
    Benchmaring with factor 0.0010
    Average time of NullIfTest: 0.32 seconds
    Average time of NullExceptionTest: 0.33 seconds
    Benchmaring with factor 0.01
    Average time of NullIfTest: 0.31 seconds
    Average time of NullExceptionTest: 0.32 seconds
    Benchmaring with factor 0.1
    Average time of NullIfTest: 0.28 seconds
    Average time of NullExceptionTest: 0.30 seconds
    Benchmaring with factor 0.9
    Average time of NullIfTest: 0.05 seconds
    Average time of NullExceptionTest: 0.04 seconds
    

    Using the server VM, the difference is hardly noticable. Still: I'd rather not use catching NullPointerException unless it really is an exception.

提交回复
热议问题