PHP – Checking Exceptions speed

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.

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

error_reporting(-1);
$time = microtime(TRUE);
$mem = memory_get_usage();

$evens = $odds = array();
foreach (range(1, 500000) as $j) {
 try {
 if ($j % 2 != 0) {
 throw new Exception("odd number");
 } else {
 $even[] = $j;
 }
 } catch (Exception $e) {
 $odd[] = $j;
 }
}
echo "evens: " . count($evens) . ", odds " . count($odds);
print_r(array('memory' => (memory_get_usage() - $mem) / (1024 * 1024), 'microtime' => microtime(TRUE) - $time));

And now the same silly script without using exceptions.

error_reporting(-1);
$time = microtime(TRUE);
$mem = memory_get_usage();

$evens = $odds = array();
foreach (range(1, 500000) as $k) {
 if ($k % 2 != 0) {
 $odds[] = $j;
 } else {
 $evens[] = $j;
 }
}

echo "odds: " . count($odds) . ", evens " . count($evens);
print_r(array('memory' => (memory_get_usage() - $mem) / (1024 * 1024), 'microtime' => microtime(TRUE) - $time));

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

*