I always thought that using "if" is much better (in terms of performance) than catching an exception. For example, by doing this:
User u = Users.getUser("Michael Jordan"); if(u!=null) System.out.println(u.getAge());
vs.
User u = Users.getUser("Michael Jordan"); try{ System.out.println(u.getAge()); }catch(Exception e){
If we compare this, it is obvious that the first fragment is faster than the second. This is what I always thought. But yesterday the guy told me something like this:
Have you ever thought about what happens in thousands of executions of your programs? Each time you perform it goes through your “if” you have a small (very small, but still something) cost of execution. Except this does not happen. Liked it never arises.
To make this clear: thousands of times have performed "if" against one exception.
I think this makes sense, but has no evidence.
Can you help me?
Thanks!!
source share