String concatenate vs implode()

Submitted by darraghenright on Sun, 02/05/2012 - 18:45

f2 is slower than f1 by 16.15%

Full source code as executed.
/*
 * How many times the code under test should run in each function
 */
define('LOOP',100000);
 
/*
 * Length of random string 
 */
define('RAND_LENGTH', 16);
 
function f1()
{
    for ($i = 0; $i < LOOP; ++$i) {
 
        $rand = '';
 
        for ($n = 0; $n < RAND_LENGTH; $n++) {
            $rand .= mt_rand(0, 9);
        }
    }
}
 
function f2()
{
    for ($i = 0; $i < LOOP; ++$i) {
 
        $rand = array();
 
        for ($n = 0; $n < RAND_LENGTH; $n++) {
            $rand[] = mt_rand(0, 9);
        }
 
        implode($rand); // assigns to nowhere ;)
    }
}
 
$start = microtime(true);
f1();
$stop = microtime(true);
$time1 = $stop - $start;
 
$start = microtime(true);
f2();
$stop = microtime(true);
$time2 = $stop - $start;
 
echo $time1 . "\t";
echo $time2 . "\n";
Test results
comparisontime1time2php_version
10.05%318492135050065.3.3-7+squeeze1
21.4%446323541837php-5.3.6-phpbrew_compiled
15.94%445489516479php-5.3.7-phpbrew_compiled
13.79%499645568533php-5.3.8-phpbrew_compiled
15.52%438588506639php-5.3.9-phpbrew_compiled
9.68%457404501661php-5.3.10-phpbrew_compiled
15.22%441978509232php-5.3.11-phpbrew_compiled
15.08%441718508351php-5.3.12-phpbrew_compiled
15.1%442319509107php-5.3.13-phpbrew_compiled
15.44%440656508675php-5.3.14-phpbrew_compiled
15.71%439052508014php-5.3.15-phpbrew_compiled
14.75%446416512268php-5.3.16-phpbrew_compiled
16.04%441878512748php-5.3.17-phpbrew_compiled
15.12%447007514574php-5.3.18-phpbrew_compiled
17.98%437419516060php-5.3.19-phpbrew_compiled
15.41%364125420228php-5.4.0-phpbrew_compiled
17.08%361801423589php-5.4.1-phpbrew_compiled
17.99%365398431120php-5.4.2-phpbrew_compiled
17.13%378785443686php-5.4.3-phpbrew_compiled
22.44%353014432222php-5.4.4-phpbrew_compiled
15.31%363317418935php-5.4.5-phpbrew_compiled
18.74%357759424803php-5.4.6-phpbrew_compiled
18.1%355848420241php-5.4.7-phpbrew_compiled
18.53%355436421285php-5.4.8-phpbrew_compiled
16.25%356632414572php-5.4.9-phpbrew_compiled
50%
updown
50%