PHP Boolean constant vs variable: speed test – which is fastest ?

Out of pure curiosity I did a test and the result was as expected: Using boolean constants is faster than variable “reference” !

The results for 100 million iterations for the functions listed below are:

  • Time 1: 3.2854 Seconds
  • Time 2: 3.7517 Seconds

The result is about 14% faster in favor of the first function: _retbool !

Here is the code for testing the execution speed in php:

<?php

function _retbool($test, &$data) {
    if ($test !== false) {
        $data = $test;   
        return true;
    }
    return false;
}

function _retvar($test, &$data) {
    $result = ($test !== false);
    if ($result !== false)
        $data = $test;       
    return $result;   
}

$data = '';

$startTime = microtime(true);

for ($i=0 ; $i<100000000 ; $i++) {
    _retbool(false, $data);
}

echo "Time 1:  " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n";

$startTime = microtime(true);

for ($i=0 ; $i<100000000 ; $i++) {
    _retvar(false, $data);
}

echo "Time 2:  " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n";

 

byrevWritten by:

Be First to Comment

    Leave a Reply

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