str_replace和str_ireplace之间是否存在性能差异?
如果是,支持哪个功能,为什么?
str_ireplace
会带来一些开销,因为它需要在比较之前将"haystack"answers"needle"都转换为小写。(c来源)然而,由于这种转换只是ascii,它的照明速度很快,不会以任何明显的方式影响性能。
这里有一个小测试:
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);
}
结果:
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
因此,对于一个包含1000000个字符的字符串,str_ireplace
只慢0.02秒。我的建议是首先优化程序的其他部分)
str_ireplace
函数php不是敏感规则,将"abc"、"abc"所有组合视为单个匹配。仅在PHP 5中可用。
str_replace
函数区分大小写,这意味着它将替换与字符串完全匹配的字符串。
str_ireplace
将不那么快,因为它需要转换为相同的情况。但在大数据中,差异将非常小。