Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Considering long time performance costs of "if" statements and exceptions

I've always thought that using a "if" is way better (in performance terms) than catching an exception. For example, 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){
   //Do something with the exception
}

If we benchmark this, it's quite obvious that the first snippet is faster than the second one. That's what i've always thought. But, yesterday, a guy told me something like this:

Have you ever considered what happens in thousands of executions of your programs? Every time your execution goes through your "if" you've a little (real little, but still something) performance cost. With exceptions it doesn't happens. Becouse it could never arise.

To make it clear: thousands of times executing an "if" vs one exception catch.

I think it has sense, but don't have any proof.

Can you help me?

Thanks!!

like image 395
santiagobasulto Avatar asked Mar 23 '11 21:03

santiagobasulto


1 Answers

No. Not once the JIT kicks in. Tell him to read up on trace caches.

A dynamic trace ("trace path") contains only instructions whose results are actually used, and eliminates instructions following taken branches (since they are not executed); a dynamic trace can be a concatenation of multiple basic blocks. This allows the instruction fetch unit of a processor to fetch several basic blocks, without having to worry about branches in the execution flow.

Basically, if the same branches are taken every time through a loop body, then that body ends up as a single trace in the trace cache. The processor will not incur the cost of fetching the extra branch instructions (unless that pushes the basic block over the limit of what can be stored in the trace cache, unlikely) and does not have to wait for the result of the test before starting to execute following instructions.

like image 157
Mike Samuel Avatar answered Nov 08 '22 21:11

Mike Samuel