php 中 str_replace或者preg_replace对php代码的性能的影响

str_replace或者preg_replace对php代码的性能的影响,如下:


$str = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
$time = array_sum(explode(' ',microtime() ) );
for($i = 0;$i < 500; $i++){
	$str = $str;
}
echo 'time is: ' .(array_sum(explode(' ',microtime() ) ) - $time).'<br />';
$time = array_sum(explode(' ',microtime() ) );
for($i = 0;$i < 500; $i++){
	$str = str_replace('dolor','dolor',$str);
}
echo 'time is: ' .(array_sum(explode(' ',microtime() ) ) - $time).'(str_replace)<br />';
$time = array_sum(explode(' ',microtime() ) );
for($i = 0;$i < 500; $i++){
	$str = preg_replace("/dolor/",'dolor', $str);
}
echo 'time is: ' .(array_sum(explode(' ',microtime() ) ) - $time).'(preg_replace)<br />';
exit;
//time is: 0.000119924545288
//time is: 0.0014500617981(str_replace)
//time is: 0.00306391716003(preg_replace)
此条目发表在php 优化分类目录。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注

看不清?