A while back I wrote a simple thing to compare the speed of preg_match v str_replace and came up with some really surprising results related to scalability. It was only done for fun, but try it yourself if you like
<?php
/* How much slower is using preg_match compared to str_replace, and is it linear?
* There are 3 tags per line. When there are
*
* 1 line: 10 / 1
* 2 lines: 23 / 1
* 4 lines: 30 / 1
* 8 lines: 44 / 1
* 16 lines 67 / 1
* 64 lines 60 / 1
* 256 lines = 40 / 1 again?
* 4096 lines - 12 / 1
*/
set_time_limit(60);
$reps1 = 100;
$reps2 = 10;
$linePow = 12;
echo "Num lines: ", pow(2, $linePow), '<br><br>';
$array = array(
'name' => 'Foo Jones',
'address' => 'Wembley Arena',
'telephone' => 'oh yes, have one'
);
$replace = "Hello my name is {name} and I live at {address} \n\nand my telephone situation is {telephone}";
// make $replace a bit longer
for ($i = 0; $i < $linePow; $i++) $replace = $replace . "<br>\n" . $replace;
$t1 = get_microtime();
for ($i = 0; $i < $reps1; $i++)
{
$r = $replace;
foreach($array as $tag => $val)
{
$r = str_replace('{' . $tag . '}', $val, $r);
}
}
$t1 = get_microtime() - $t1;
echo "t1: $t1<br><br>";
$t2 = get_microtime();
for ($i = 0; $i < $reps2; $i++)
{
$r = $replace;
$r = preg_replace('%{([^}]*)}%e', '$array["\\1"]', $r);
}
$t2 = get_microtime() - $t2;
echo "t2: $t2";
echo '<br>Ratio t2 / t1: ', ($reps1 * $t2) / ($t1 * $reps2);
function get_microtime()
{
list($sec, $usec) = explode(' ', microtime());
return (float)$sec + (float)$usec;
}
?>
str_replace races ahead, but then the lead peaks and falls back as the amount of data being sifted grows.