搞砸了,我做了一个基准:
$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
它显然不会遍历字符串但返回预先索引的值.没有速度差异.