Forum Moderators: coopster
When I began to code in PHP I saw a lot of examples using the concatenation operators "." or ".=". Being used to the array approach I tended to use that one in PHP as well. However, I have always wondered whether this was the way to go in PHP too.
Today I tested it finally.
Code
<?php
/*
Comparing speed of concatenating strings
and pushing and joining arrays
*/
#
function getmicrotime($t) {
list($usec, $sec) = explode(" ",$t);
return ((float)$usec + (float)$sec);
}
#
$x = array('Taylor','Zac','Isaac','Leo','Aaron','Nick','Scott',
'Dave','Bob','Clint','Chris','Thomas','Ryan','Dennis',
'Thimo','Steve');
#
$s1 = microtime();
foreach($x as $val) {
$s .= $val . ', ';
}
echo $s, '<br>';
$e1 = microtime();
#
unset($s);
$s = array();
#
$s2 = microtime();
foreach($x as $val) {
array_push($s, $val);
}
$y = implode(', ', $s);
echo $y, '<br>';
$e2 = microtime();
#
$t1 = (getmicrotime($e1) - getmicrotime($s1));
$t2 = (getmicrotime($e2) - getmicrotime($s2));
$td = $t1 - $t2;
#
echo "using concat: $t1 seconds<br>
using array: $t2 seconds<br><br>
difference: $td seconds";
?>
Output
Taylor, Zac, Isaac, Leo, Aaron, Nick, Scott, Dave, Bob, Clint, Chris, Thomas, Ryan, Dennis, Dave, Steve,
Taylor, Zac, Isaac, Leo, Aaron, Nick, Scott, Dave, Bob, Clint, Chris, Thomas, Ryan, Dennis, Dave, Steve
using concat: 0.000538945198059 seconds
using array: 0.00032103061676 seconds
difference: 0.000217914581299 seconds
Conclusion
Donīt use the concatenation operator. Pushing the string parts into an array and then joining the array is about 40% faster. Additionally in a lot of cases of makes your job way easier if you want to add some glue string between the elements but not after the last one.
Andreas
And to quote from another thread [webmasterworld.com]:
And I thought no one cared... ;)