PHP中strlen()的效率是多少?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了PHP中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 seconds\n";

$time=microtime(true);
for($run=0;$run<100000000;$run++)
    $temp2=strlen($longstring);
$time=microtime(true)-$time;

echo "strlen on long string took $time seconds\n";

结果

strlen on short string took 12.508891820908 seconds
strlen on long string took 11.897696971893 seconds

它显然不会遍历字符串但返回预先索引的值.没有速度差异.

脚本宝典总结

以上是脚本宝典为你收集整理的PHP中strlen()的效率是多少?全部内容,希望文章能够帮你解决PHP中strlen()的效率是多少?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。