Hey all, I was playing around this morning with a little test to decide
whether string substitution is faster or slower than concatenation. I
figured that, since printing variable values is one of the most common
actions in a script finding which method is best would be important.
I've been suspecting that string substitution was slower and have tried
not to use it as a general rule of thumbs.

I found it sort-of interesting that--at least according to my
test--string substitution is significantly slower than concatenation by
quite a bit (like 40%).

Here's my script--let me know if you find any flaws that skew the
results:

<?

$num_tries = 500000;

function print_microtime($t)
{
        $t = explode (' ', $t);
        return number_format ($t[1]+$t[0], 10);
}
function print_microtime_diff($t1, $t2, &$res)
{
        $t1 = explode (' ', $t1);
        $t2 = explode (' ', $t2);

        $res = ($t2[1] + $t2[0]) - ($t1[1] + $t1[0]);

        return number_format ($res, 10);
}


$start = microtime();

$s = 'test string';

for ($i = 0; $i < $num_tries; $i++)
        $a = 'test ' . $s . ' string';

$end = microtime();

echo "Normal concatenation\n";
echo 'Start: ' . print_microtime($start) . "\n";
echo 'End:   ' . print_microtime($end) . "\n";
echo 'Diff:  ' . print_microtime_diff ($start, $end, $diff1) . "\n\n";

$start = microtime();

$s = 'test string';

for ($i = 0; $i < $num_tries; $i++)
        $a = "test $s string";

$end = microtime();

echo "String substitution\n";
echo 'Start: ' . print_microtime($start) . "\n";
echo 'End:   ' . print_microtime($end) . "\n";
echo 'Diff:  ' . print_microtime_diff ($start, $end, $diff2) . "\n\n";

echo 'Difference in timing: ' . ($diff2 - $diff1) . ' (' . number_format
(($diff2 - $diff1) / $diff1 * 100, 2) . "%)\n\n";

?>




-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to