2

Someone extremely smart at work told me try catches which don't throw will affect performance on a site with millions of users. based on the unit test posted showing equal performance, I'm wondering if this is related to an os level and/or web server specific situation. For instance, web server's implementation of asynchronous work occurs on child processes instead of threads.

Anyone know?

What I'd like to see is an output of a php profiler showing actual cpu time used.

jmucchiello's comment on Performance of try-catch in php is interesting, but doesn't measure cpu time used.

Thanks, David

Community
  • 1
  • 1
davidjnelson
  • 1,111
  • 12
  • 22
  • Why not ask the 'extremely smart' person at work for some evidence? (Could be tricky to phrase I suppose depending on any heirarchy that may be in place.) :-) – John Parker Jan 27 '10 at 20:11

1 Answers1

12

I ran a very small and unscientific test and found there to be roughly no difference between having a catch that never gets called or having it outside a try catch statement. I ran each of these two scripts 5 times each through my profiler and averaged the total times.

Results

  • With Try/Catch statement: 1.34 seconds
  • Without Try/Catch statement: 1.3 seconds

The Code

Try/Catch

<?php
foreach(range(1,200000) as $i) {
    try {
         if ($i % 5 == 0 && $i % 3 == 0)    echo "fizzbuzz";
         elseif ($i % 5 == 0)               echo "fizz";
         elseif ($i % 3 == 0)               echo "buzz";
         else                               echo $i;
     } catch (Exception $e) {
         echo sin($i) * cos($i * pi());
     }
}

?>

No Try/Catch

<?php
foreach(range(1,200000) as $i) {
     if ($i % 5 == 0 && $i % 3 == 0)    echo "fizzbuzz";
     elseif ($i % 5 == 0)               echo "fizz";
     elseif ($i % 3 == 0)               echo "buzz";
     else                               echo $i;
}

?>
Community
  • 1
  • 1
TJ L
  • 23,914
  • 7
  • 59
  • 77
  • I agree it is not scientific etc, but the two code are not doing equal effective computation (so to speak). The "Try/Catch" one has very expensive arithmetic operations in the loop, within the catch block! – ϹοδεMεδιϲ Jan 16 '14 at 13:31
  • 1
    @ϹοδεMεδιϲ The idea was that I wanted something expensive there so it would throw off the execution time, making it obvious that code in a catch statement that never gets hit will have no effect on execution time. – TJ L Jan 16 '14 at 17:32