Is there a performance difference between str_replace and str_ireplace?
If yes, in favour of which function and why?
str_ireplace
imposes a little overhead because it needs to convert both "haystack" and "needle" to lowercase before comparison. (c source) However, since this conversion is ascii-only, it's lighting fast and won't affect performance in any noticeable way.
Here's a little test:
for($i = 2; $i < 7; $i++) {
$x = str_repeat('a', pow(10, $i));
$t = microtime(1); str_replace ('a', 'b', $x); $a = microtime(1) - $t;
$t = microtime(1); str_ireplace('A', 'b', $x); $b = microtime(1) - $t;
$t = microtime(1); strtolower($x); $c = microtime(1) - $t;
printf("%d replace=%.4f ireplace=%.4f lower=%.4f\n", $i, $a, $b, $c);
}
Results:
2 replace=0.0000 ireplace=0.0000 lower=0.0000
3 replace=0.0000 ireplace=0.0000 lower=0.0000
4 replace=0.0002 ireplace=0.0003 lower=0.0001
5 replace=0.0021 ireplace=0.0030 lower=0.0008
6 replace=0.0253 ireplace=0.0441 lower=0.0110
So, for a string of 1,000,000 characters str_ireplace
is only 0.02 sec "slower". My suggestion is to optimize other parts of your program first ))