php字符串替换函数strtr str_replace preg_replace效率对比

php技巧

前面一篇具体说了strtr这个函数的使用注意点,同时我知道有人说strtr比str_replace快4倍
然而我测试得到结果却是让人失望
strtr在strtr(string,array)用法的时候,它比str_replace更慢些。
10w次的两个词替换结果表明
str_replacece 耗时0.38 sec.
strtr 耗时0.52sec.
preg_replace 耗时0.97sec.

不需要测试都应该知道preg_replace肯定最慢

只是两个语句的执行

1
2
$str_replace_str = str_replace('喜欢','非常喜欢',$str);
$str_replace_str = str_replace('奥运','北京',$str_replace_str);

却要比一句的

1
$strtr_str = strtr($str,array('喜欢'=>'非常喜欢','奥运'=>'北京'));

的速度还快

ps:被替换的句子

1
$str = '我喜欢运动,我喜欢奥运,我更喜欢参加奥运,欢迎喜欢奥运的人齐聚北京!';

但是,strtr在strtr(string,from,to)这样的用法下仍然是最快的,只不过,没法常用罢了。

Leave a Reply

Icons by N.Design Studio. Designed By Ben Swift. Powered by WordPress and Free WordPress Themes
Entries RSS Comments RSS Log in