Ni
..would like a shrubbery.
Posts: 4,822
Well, I'd assume join() will be slower than implode() because it's an alias but I didn't test implode or join. I'd assume php needs to parse and store an array in memory then iterate through it so would expect it to be a fair bit slower than concatenation.
Actually I'll try it:
[php]
<?php
$iterations = 500000;
$name = 'Tom';
$date = '13/09/2009';
$t1 = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$str = sprintf('Hi %s, you last logged in on %s.', $name, $date);
}
$t2 = microtime(true);
echo 'sprintf: ' . ($t2-$t1);
echo '<br />';
$t1 = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$str = 'Hi ' . $name . ', you last logged in on ' . $date;
}
$t2 = microtime(true);
echo 'concat: ' . ($t2-$t1);
echo '<br />';
$t1 = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$str = implode(array('Hi ', $name, ' you last logged in on ', $date, '.'));
}
$t2 = microtime(true);
echo 'implode: ' . ($t2-$t1);
echo '<br />';
$t1 = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$str = join(array('Hi ', $name, ' you last logged in on ', $date, '.'));
}
$t2 = microtime(true);
echo 'join: ' . ($t2-$t1);
?>
[/php]
Results in:
heh, funnily enough implode is actually marginally slower. I guess because the function name is longer so the parser has more to look at.
Not that these micro-optimisations are really worthwhile. My main complaint with sprintf was maintainability.
TheJkWhoSaysNiTheJkWhoSaysNiTheJkWhoSaysNiTheJkWho
SaysNiTheJkWhoSaysNiTheJkWhoSaysNiTheJkWhoSaysNiTh
eJkWhoSaysNiTheJkWhoSaysNiTheJkWhoSaysNiTheJkWhoSa
ysNiTheJkWhoSaysNiTheJkWhoSaysNiTheJkWhoSaysNiTheJ
kWhoSaysNiTheJkWhoSaysNiTheJkWhoSaysNiTheJkWhoSays
NiTheJkWhoSaysNiTheJkWhoSaysNiTheJkWhoSaysNiTheJkW