I'm looking at trying to optimise a particular function in a PHP application and foolishly assumed that a boolean lookup in an 'if' statement would be quicker than a string compare. But to check it I put together a short test (see below) using microtime. To my surprise, the string lookup was quicker.
Is there anything wrong with my test (I'm wired on too much coffee, so I'm suspicious of my own code)? If not, I would be interested in any comments people have around string versus boolean lookups in PHP.
The result for the first test (boolean lookup) was 0.168 seconds.
The result for the second test (string lookup) was 0.005 seconds.
<?php
$how_many = 1000000;
$counter1 = 0;
$counter2 = 0;
$abc = array('boolean_lookup'=>TRUE, 'string_lookup'=>'something_else');
$start = microtime();
for ($i = 0; $i < $how_many; $i++)
{
if ($abc['boolean_lookup'])
{
$counter1++;
}
}
echo ($start - microtime());
echo '<hr>';
$start = microtime();
for ($i = 0; $i < $how_many; $i++)
{
if ($abc['string_lookup'] == 'something_else')
{
$counter2++;
}
}
echo ($start - microtime());