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

Ala*_*air 5 php strlen

使用strlen实际上是通过迭代字符串来计算字符串中的字节数,还是简单地从索引返回已经计算的字符串长度的值?

我的问题的原因是因为我可以选择为速度敏感的脚本存储非常长字符串的预先计算值,或者我可以使用该strlen函数并节省自己的编码时间.

但我真的想知道我是如何strlen工作的,因为我倾向于依赖它,也许这不是一个好主意?

UPDATE

请参阅下面的基准.

Ala*_*air 6

搞砸了,我做了一个基准:

<?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";
Run Code Online (Sandbox Code Playgroud)

结果

strlen on short string took 12.508891820908 seconds
strlen on long string took 11.897696971893 seconds
Run Code Online (Sandbox Code Playgroud)

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