Alex Rivera | Logout

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

Asked 2010-08-16T05:21:41.767
36

Which one is faster:

Either this

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

or

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

1 Answer

2

It is usually expensive to handle exceptions. The VM Spec might give you some insight into how much, but in the above case if (n != null) n.foo(); is faster.

Although I agree with Mitch Wheat regarding the real question is correctness.

@Mitch Wheat - In his defense this is a pretty contrived example. :)

answered 2010-08-16T05:29:37.060

Your Answer