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

标签 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";

结果:

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/

相关文章:

c++ - 按位异或与求和之间的性能差异似乎不大

javascript - 硫化破坏了 polymer 代码(未捕获的类型错误 : undefined is not a function)

php - 警告:strlen()期望参数1为字符串,给定[duplicate]数组

PHP MySQLi 查询不工作

php - 如何在 CodeIgniter 中包含/使用 Composer Bootstrap?

php - 为什么我得到 mysql_connect() : Lost connection to MySQL server and how can I fix it?

c - 检查字符串卡住的函数

php - 从mysql数据库获取一个 "cell"

java - System.currentTimeMillis() 是 Java 中时间性能的最佳衡量标准吗?

assembly - 如何在 Assembly 中使用 scasb 查找字符串长度