Home > Backend Development > PHP Tutorial > php中关于处理字符串时效率的讨论_PHP

php中关于处理字符串时效率的讨论_PHP

WBOY
Release: 2016-06-01 12:29:34
Original
831 people have browsed it

  有一堆类似以下变量$abc的字符串,末尾都多出来了一个,(逗号),我想去掉末尾的逗号,为了验证不同的处理方法的执行时间,以下是我写的一个对比程序进行试验:

  程序一,利用substr

function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec (float)$sec);
}

$time_start = getmicrotime();

$abc="重庆,万州,涪陵,渝中,大渡口,江北,沙坪坝,九龙坡,南岸,北碚,万盛,双挢,渝北,巴南,黔江,长寿,綦江,潼南,铜梁,大足,荣昌,壁山,梁平,城口,丰都,垫江,武隆,忠县,开县,云阳,奉节,巫山,巫溪,石柱,";

$l=strlen($abc);
$abc=substr($abc,0,$l-1);
echo $abc."
";
$time_end = getmicrotime();
echo ($time_end-$time_start)*1000;
?>

  程序二,利用正则表达式

function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec (float)$sec);
}

$time_start = getmicrotime();

$abc="重庆,万州,涪陵,渝中,大渡口,江北,沙坪坝,九龙坡,南岸,北碚,万盛,双挢,渝北,巴南,黔江,长寿,綦江,潼南,铜梁,大足,荣昌,壁山,梁平,城口,丰都,垫江,武隆,忠县,开县,云阳,奉节,巫山,巫溪,石柱,";

$abc=str_replace(",$","",$abc);
echo $abc."
";
$time_end = getmicrotime();
echo ($time_end-$time_start)*1000;
?>

  结果程序一的执行平均时间为0.045,程序二的执行平均时间为0.085。不进行任何处理的平均执行时间为0.041

  可见利用第一种方法处理效率要高出尽50%

  由此,我们在做程序的过程中,尤其是在要求高效的程序中,我们应该对不同的方法进行一下对比,找出最优化的处理方法。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template