claudioimai;10899454 wrote:Hi.
I just pointed that because it looked simpler to use a regex in this case (less code).
Less code does not necessarily = faster. It is possible to have less code bloat, but have those code components be heavier in execution times.
Functions like str_replace tend to be faster than their preg / ereg replace counter parts, even with about the same amount of code.
Consider the test results of the following:
$str = 'I am Mr.X';
echo 'String: "' . $str . '"<br /><br />';
$loop = 10000;
$time_start = microtime(true);
for($i = 0; $i < $loop; $i++){
$result = str_replace('X', 'Y', $str);
}
$time_end = microtime(true);
$elapsed_time = round($time_end-$time_start, 4);
echo 'Method: str_replace(\'X\', \'Y\', $str)<br />Time: ' . $elapsed_time . '<br />Result: "' . $result . '"<br /><br />';
$time_start = microtime(true);
for($i = 0; $i < $loop; $i++){
$result = preg_replace('#X#', 'Y', $str);
}
$time_end = microtime(true);
$elapsed_time = round($time_end-$time_start, 4);
echo 'Method: preg_replace(\'#X#\', \'Y\', $str)<br />Time: ' . $elapsed_time . '<br />Result: "' . $result . '"<br /><br />';
$time_start = microtime(true);
for($i = 0; $i < $loop; $i++){
$result = ereg_replace('X', 'Y', $str);
}
$time_end = microtime(true);
$elapsed_time = round($time_end-$time_start, 4);
echo 'Method: ereg_replace(\'X\', \'Y\', $str)<br />Time: ' . $elapsed_time . '<br />Result: "' . $result . '"<br /><br />';
Sample output:
String: "I am Mr.X"
Method: str_replace('X', 'Y', $str)
Time: 0.0277
Result: "I am Mr.Y"
Method: preg_replace('#X#', 'Y', $str)
Time: 0.08
Result: "I am Mr.Y"
Method: ereg_replace('X', 'Y', $str)
Time: 0.105
Result: "I am Mr.Y"
Now in a single pass, the speed difference between the these would be practically inperceptable... but in this case, I increased the loop to 10,000 times..as you can see, str_replace is faster, yet all functions output the same thing (with about the same amount of code).