当字符串大小无关紧要时,为什么strlen()比使用变量慢?

Tom*_*ica 2 php performance strlen

我正在编写一些简单的文件操作,如果我将字符串大小保存在变量中会不会更快,我会想到一个想法.它表明它快了10倍.
使用此代码:

include "../classes/Timer.class.php";
$t = new Timer();             //Timer class I've written for this purpose [link below]
$multiplyer = 3000000;        //Times to try the operation
$string = str_repeat("ggggggggggg",2);  //I first tried 2000 here, but for 2 there are same results
$t("calling");     //Saving time
for($i=0; $i<$multiplyer; $i++) {
  $size =  strlen($string);
  $size2 = strlen($string);
  $size3 = strlen($string);
}
$t("clover");
$t("caching");     //Saving time
for($i=0; $i<$multiplyer; $i++) {
  $size =  strlen($string);
  $size2 = $size;
  $size3 = $size;
}
$t("chover");
$total = $t["calling-clover"]+$t["caching-chover"];  //percents are usefull :)
echo "Calling: {$t["calling-clover"]} (".round(($t["calling-clover"]/$total)*100)."%)<br>\n";
echo "Caching in variables: {$t["caching-chover"]} (".round(($t["caching-chover"]/$total)*100)."%)<br>\n";
Run Code Online (Sandbox Code Playgroud)

结果:

呼叫:1.988455057(67%)
变量缓存:0.984993458(33%)

更有趣的是,事实是,我在str_repeat调用中输入的数字并不重要,因此strlen显然不会计算任何东西 - 大小必须保存在某个地方,而且strlen只是返回值的函数.
这意味着:
函数调用真的很慢吗?
如果没有,这是strlen具体的吗?


Timer.class.php

slu*_*ion 8

这更符合科林的回答

更有意思的是,我在str_repeat调用中输入的数字并不重要,因此strlen显然不会计算任何东西 - 大小必须保存在某处,而strlen只是返回值的函数.

这是对的.在潜水源中潜水了很长一段时间后,我最终走到了这条线上:

#define Z_STRLEN(zval)                  (zval).value.str.len
Run Code Online (Sandbox Code Playgroud)

所以是的,strlen的值计算一次并缓存.