«

»

Jan 20

Checking PHP Exceptions’ speed

We sometimes use exceptions to manage the flow of our scripts. I guess the use of exceptions should cause a lack in performance. To verify this, I will do a small benchmark test to measure the performance difference in execution of a simple script configured to throw exceptions and once without them.
So let’s begin

First a not so useful script to find odd numbers (it’s just for the bench marking purposes :) )

And now the same silly script without using exceptions.

 

The outcomes are as follows:

  • with exceptions
    memory: 15.329871597534
    microtime: 2.1678985214796
  • without exceptions
    memory: 15.216841537290
    microtime: 0.2632134548652

As we can see the exploitation of memory is approximately the same. But the script turns out to be almost ten times faster without the use of exceptions.

I have performed these tests using apache on my PC with 2048 MB of memory and PHP 5.3
Now we are going to execute the tests with an almost similar host. This time the same configuration, but PHP 5.4 instead of 5.3

waiting for the results? Let’s see!

PHP 5.4:

  • With exceptions
    memory: 10.574567984512
    microtime: 0.23456897254687
  • without exceptions
    memory: 10.569843616487
    microtime: 0.10698432145785

I’m very much impressed with the results. The memory usage here in PHP 5.4 is much efficient now and better run time too (nearly ten times faster).

The results indicate that my conclusion is that the use of exceptions in the flow of our scripts is not as bad as I thought. OK, in this example, the use of exceptions is not a good idea, but other exceptions, if used in complex scripts prove to be really useful. I must also take into account the tests when done over 100,000 iterations so as to get a general idea in the performance differences.

Conclusion
I will continue to use exceptions in my scripts (I don’t code even and odd numbers!! :) ). This type of micro-optimization does not seem to be of much use to me. What’s your take on it?