和 ==
之间的区别, ===
当我确定两个操作数是同一类型时, ==
或与 ===
进行比较哪个更快
简短而普遍的回答是: There is no performance gain in using ===
in this cases, so you should probably use ==
.
对于那些有兴趣自己进行基准测试的人,你可以使用我临时编写的以下代码并尝试不同的 $a
和 $b
:
<?php
// CONFIGURATION
$cycles = 1000000;
$a = 'random string 1';
$b = 'random string 2';
// FUNCTIONS
function compare_two_equals($a, $b) {
if ($a == $b) {
return TRUE;
} else {
return FALSE;
}
}
function compare_three_equals($a, $b) {
if ($a === $b) {
return TRUE;
} else {
return FALSE;
}
}
// EXECUTION
$time = microtime(TRUE);
for ($count_a = 0; $count_a < $cycles; $count_a++) {
compare_two_equals($a, $b);
}
$time_two_a = microtime(TRUE) - $time;
$time = microtime(TRUE);
for ($count_a = 0; $count_a < $cycles; $count_a++) {
compare_three_equals($a, $b);
}
$time_three_a = microtime(TRUE) - $time;
$time = microtime(TRUE);
for ($count_a = 0; $count_a < $cycles; $count_a++) {
compare_two_equals($a, $b);
}
$time_two_b = microtime(TRUE) - $time;
$time = microtime(TRUE);
for ($count_a = 0; $count_a < $cycles; $count_a++) {
compare_three_equals($a, $b);
}
$time_three_b = microtime(TRUE) - $time;
$time = microtime(TRUE);
// RESULTS PRINTING
print "<br />\nCOMPARE == (FIRST TRY): " . number_format($time_two_a, 3) . " seconds";
print "<br />\nCOMPARE == (SECOND TRY): " . number_format($time_two_b, 3) . " seconds";
print "<br />\nCOMPARE === (FIRST TRY): " . number_format($time_three_a, 3) . " seconds";
print "<br />\nCOMPARE === (SECOND TRY): " . number_format($time_three_b, 3) . " seconds";
?>
注意:只有当每次“第一次尝试”与其“第二次尝试”非常接近时,比较才有效。如果它们明显不同,则意味着处理器在执行比较时正忙于执行其他操作,因此结果不可靠,应再次运行基准测试。