对于我的一个应用程序,我认为比较2个字符串的第一个字符比比较整个字符串的速度要快。例如,如果我知道只有两个可能的字符串(在一组字符串中)可以以同一个字母开始(比如'q'),如果是这样,它们是相同的字符串,那么我可以写一个比较像这样:PHP - 为什么比较两个整个长(相同)的字符串比比较每个字符的第一个字符要快得多?
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?字符串是硬编码的,从文件读取还是动态生成? – axiac
最有可能是由于zval引用效应 – hindmost
这个用例只有硬编码...在我的应用程序字符串动态生成 –