我正在编写一些简单的文件操作,然后想到如果我将字符串大小保存在变量中会不会更快。结果表明它快了 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";
结果:
Calling: 1.988455057 (67%)
Caching in variables: 0.984993458 (33%)
更有趣的是,我在 str_repeat
调用中输入什么数字并不重要,因此 strlen
显然不计算任何东西 -大小必须保存在某处,strlen
只是返回值的函数。
这意味着:
函数调用真的这么慢吗?
如果不是,这个strlen
是特定的吗?
Timer.class.php
最佳答案
这更符合 Colin 的回答
What is even more interesting is the fact, that it does not matter what number I put in the str_repeat call, so the strlen obviously does not compute anything - the size must be saved somewhere and strlen is just function that returns value.
这是正确的。在深入研究源代码一段时间后,我来到了这一行:
#define Z_STRLEN(zval) (zval).value.str.len
是的,strlen 的值计算一次并缓存。
关于php - 当字符串大小无关紧要时,为什么 strlen() 比使用变量慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14835246/