Return to Snippet

Revision: 800
at August 9, 2006 09:23 by mthorn


Initial Code
$time_start = microtime(true);

for ( $i = 0; $i < 100000; ++$i )
{
   $results = strcmp('string' + $i, 'string' + $i);
}

$time_end = microtime(true);
printf("strcmp with matching strings took %f seconds\n", $time_end - $time_start);

$time_start = microtime(true);

for ( $i = 0; $i < 100000; ++$i )
{
   $results = strcmp('string' + $i, 'string' + ($i + 1));
}

$time_end = microtime(true);
printf("strcmp with non-matching strings took %f seconds\n", $time_end - $time_start);

$time_start = microtime(true);

for ( $i = 0; $i < 100000; ++$i )
{
   $results = ('string' + $i) === ('string' + $i);
}

$time_end = microtime(true);
printf("=== with matching strings took %f seconds\n", $time_end - $time_start);

$time_start = microtime(true);

for ( $i = 0; $i < 100000; ++$i )
{
   $results = ('string' + $i) === ('string' + ($i + 1));
}

$time_end = microtime(true);
printf("=== with non-matching strings took %f seconds\n", $time_end - $time_start);

Initial URL
http://www.mthorn.net

Initial Description
strcmp with matching strings took 0.207852 seconds
strcmp with non-matching strings took 0.215276 seconds
=== with matching strings took 0.067122 seconds
=== with non-matching strings took 0.057305 seconds

=== is the clear winner. Function calls are always slower than operators. This was with PHP5, may be different for earlier versions. Not sure about the memory impact but I assume it's less since the strings do not have to be copied for the function call.

Initial Title
Speed Test: strcmp vs ===

Initial Tags
php

Initial Language
PHP