PHP中strlen()的效率是多少?
发布时间:2020-12-13 17:23:28 所属栏目:PHP教程 来源:网络整理
导读:使用strlen实际上是通过遍历字符串来计算字符串中的字节数,还是简单地从索引返回已经计算的字符串长度的值? 我的问题的原因是因为我可以选择为速度敏感的脚本存储非常长字符串的预先计算的值,或者我可以使用strlen函数并节省自己的编码时间. 但我真的想知道
使用strlen实际上是通过遍历字符串来计算字符串中的字节数,还是简单地从索引返回已经计算的字符串长度的值?
我的问题的原因是因为我可以选择为速度敏感的脚本存储非常长字符串的预先计算的值,或者我可以使用strlen函数并节省自己的编码时间. 但我真的想知道strlen是如何工作的,因为我倾向于依赖它很多,也许这不是一个好主意? UPDATE 请参阅下面的基准. 解决方法
搞砸了,我做了一个基准:
<?php $shortstring='hello'; $longstring='long'; for($run=0;$run<100000;$run++) $longstring.='dsffghdgfhdsda'.rand(1000,2000); $time=microtime(true); for($run=0;$run<100000000;$run++) $temp=strlen($shortstring); $time=microtime(true)-$time; echo "strlen on short string took $time secondsn"; $time=microtime(true); for($run=0;$run<100000000;$run++) $temp2=strlen($longstring); $time=microtime(true)-$time; echo "strlen on long string took $time secondsn"; 结果 strlen on short string took 12.508891820908 seconds strlen on long string took 11.897696971893 seconds 它显然不会遍历字符串但返回预先索引的值.没有速度差异. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |