Thursday, March 5, 2009

Try catch vs if statements

Many might already know this but I wanted to know for sure. Is it faster to use a try catch block or if statement. So I ran a simple test to find out. I created this function to run the try catch test;

private function testTryCatch() : void {
 var adder:Function = function a( x: int ) : int {
  return (x + 1);
 };

 var x:int = 0;
 var o:Object = { 0 : adder };

 for( var i:int = 0; i < 1000000; i++ ){
  var y:int = i % 2;
  try{ 
   x = o[y]( x );
  }
  catch( except:Object ){
   x = adder(x);
  }
 }
}

I then wrote an identical function except that it had an if( o[y] != null ) statement where the try was. Now what I found was that the if statement times did not change it took 0.57 seconds in all the tests. However, the try catch statements did not preform quite as well. As the number of exceptions are thrown the amount of time increases rapidly. Here is a table of times for the percentage of exceptions thrown over a million iterations.

0% 33% 50% 90%
0.5 4.219 6.031 10.422


I ran the function without the try catch/if statement and it took 0.422 seconds. If I subtract that from the times and then divide the number of exceptions thrown by the time you end up about 90,000 for each of the times. To put it another way, on my computer I can throw 90,000 exceptions per second.

So it seems like unless you are really do not like if statements it would be faster to use them.

No comments:

Post a Comment