【发布时间】:2016-05-16 20:44:15
【问题描述】:
对于我的一个应用程序,我假设比较 2 个字符串的第一个字符会比比较整个字符串的相等性更快。例如,如果我知道只有 2 个可能的字符串(在一组 n 字符串中)可以以相同的字母开头(比如说一个 'q'),如果是这样,它们是相同的字符串,那么我可能会写一个这样的比较:
if ($stringOne[0] === $stringTwo[0]) $qString = true;
代替:
if ($stringOne === $stringTwo) $qString = true;
但我最近写了一些基准脚本,似乎我假设错了。也就是说,看起来第二次比较平均比第二次快 2-4 倍。我的基准是这样的:
$x = 'A really really looooooooooooong string';
$y = 'A really really looooooooooooong string';
$timeArray = array();
//Method 1, two-four times faster than Method 2
for($i = 0; $i < 100; $i++) {
$t1 = microtime(true);
for($j = 0; $j < 100000; $j++) {
if ($x === $y) continue;
}
$t2 = microtime(true);
$timeArray[] = $t2 - $t1;
}
echo array_sum($timeArray) / 100;//average time is echoed
//Method 2
for($i = 0; $i < 100; $i++) {
$t1 = microtime(true);
for($j = 0; $j < 100000; $j++) {
if ($x[0] === $y[0]) continue;
}
$t2 = microtime(true);
$timeArray[] = $t2 - $t1;
}
echo array_sum($timeArray) / 100;//average time is echoed
我想我假设由于每个字符串 $x 和 $y 都在内存中,那么每个字符串的第一个字符也在内存中,并且比较会更快。
为什么全字符串比较更快?从每个字符串中提取第一个字符进行比较是否有“成本”?
更新:即使在每次外部循环迭代中生成新字符串并进行比较,或者起始字符串是否相同,Method1 对我来说仍然比 Method2 快。
//Method 1 faster than Method 2 by 2-3 times
for($i = 0; $i < 100; $i++) {
$t1 = microtime(true);
$a = $x . $i;
$b = $y . $i;
for($j = 0; $j < 100000; $j++) {
if ($a === $b) continue;
}
$t2 = microtime(true);
$timeArray[] = $t2 - $t1;
}
//Method 2
for($i = 0; $i < 100; $i++) {
$t1 = microtime(true);
$a = $x . $i;
$b = $y . $i;
for($j = 0; $j < 100000; $j++) {
if ($a[0] === $b[0]) continue;
}
$t2 = microtime(true);
$timeArray[] = $t2 - $t1;
}
如果通过严格不等价而不是严格等价比较两者,也会得到相同的结果
//Method 1 faster than Method 2 by 1.5-2 times, but now less of a difference
for($i = 0; $i < 100; $i++) {
$t1 = microtime(true);
$a = $x . $i;
$b = $y . $i;
for($j = 0; $j < 100000; $j++) {
if ($a !== $b) continue; // using inequivalence this time
}
$t2 = microtime(true);
$timeArray[] = $t2 - $t1;
}
//Method 2
for($i = 0; $i < 100; $i++) {
$t1 = microtime(true);
$a = $x . $i;
$b = $y . $i;
for($j = 0; $j < 100000; $j++) {
if ($a[0] !== $b[0]) continue; // using inequivalence this time
}
$t2 = microtime(true);
$timeArray[] = $t2 - $t1;
}
【问题讨论】:
-
什么版本的 PHP?字符串是硬编码的、从文件中读取的还是动态生成的?
-
很可能是由于 zval 引用效应
-
对于这个用例只有硬编码...在我的应用程序字符串是动态生成的
标签: php performance