php string versus boolean speed test
- by ae
I'm looking at trying to optimise a particular function in a php app and foolishly assumed that a boolean lookup in a 'if' statement would be quicker than a string compare. But to check it I put together a short test (see below). 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
The result for the second test (string lookup) was 0.005
<?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());