Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string versus boolean speed test

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());
like image 787
ae. Avatar asked Aug 01 '26 20:08

ae.


1 Answers

Yes, you've had too much coffee. You need to use microtime(true) otherwise your date calculations are working on the milliseconds but completely ignoring seconds. Also, use current time - start time to measure duration, not start time - current time, or else you get a negative time. Try the following code instead:

<?php

$how_many = 5000000;
$counter1 = 0;
$counter2 = 0;

$abc = array('boolean_lookup'=>TRUE, 'string_lookup'=>'something_else');

$start = microtime(true);
for($i = 0; $i < $how_many; $i++)
{
    if($abc['boolean_lookup'])
    {
        $counter1++;
    }

}

echo "FIRST: ", (microtime(true) - $start), "\n";

$start = microtime(true);
for($i = 0; $i < $how_many; $i++)
{
    if($abc['string_lookup'] == 'something_else')
    {
        $counter2++;
    }

}

echo "SECOND: ", (microtime(true) - $start), "\n";
like image 57
too much php Avatar answered Aug 03 '26 10:08

too much php



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!