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

前端 未结 12 1987
暖寄归人
暖寄归人 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:50

    The if construct is faster. The condition can be easily translated to machine code (processor instructions).

    The alternative (try-catch) requires creating a NullPointerException object.

提交回复
热议问题