本篇文章是对strtr, str_replace和preg_replace三个函数的效率问题进行了详细的分析介绍,需要的朋友参考下
之前已经分析过strtr的源码了,现在就比较strtr, str_replace和preg_replace的效率:
复制代码 代码如下:
$str =
'111111110000000000000000000000000000000111000001000100010000010010000010010000010100000010
';
$str = str_repeat($str, 1);
$pattern1 = array('12345'=>'', '67891'=>'');
$pattern2 = array('a'=>'', '1234567890'=>'');
$pattern3 = '/12345|67891/';
$pattern4 = '/a|1234567890/';
$pattern5 = array('12345', '67891');
$pattern6 = array('a', '1234567890');
$t = microtime(true);
for($i=0; $i{
strtr($str, $pattern1);
}
echo microtime(true)-$t, "/n";
//0.21915886878967 0.47268319129944
$t = microtime(true);
for($i=0; $i{
strtr($str, $pattern2);
}
echo microtime(true)-$t, "/n";
//0.4768660068512 2.7257590293884
$t = microtime(true);
for($i=0; $i{
preg_replace($pattern3, '', $str);
}
echo microtime(true)-$t, "/n";
//0.30504012107849 1.0864448547363
$t = microtime(true);
for($i=0; $i{
preg_replace($pattern4, '', $str);
}
echo microtime(true)-$t, "/n";
//0.30298089981079 1.117014169693
$t = microtime(true);
for($i=0; $i{
str_replace($pattern5, '', $str);
}
echo microtime(true)-$t, "/n";
//0.18029189109802 0.22510504722595
$t = microtime(true);
for($i=0; $i{
str_replace($pattern6, '', $str);
}
echo microtime(true)-$t, "/n";
//0.18104100227356 0.23055601119995
//说明:当str_repeat的第二个参数为1时输出第一个数字,当为8时输出第二个数字
复制代码 代码如下:
str_replace(array('ab', 'abc'), '1', 'abcd');