Tests on
- Win 11
- Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz 2.21 GHz
- 64Gb RAM,
- PHP 8.1.10 (in Tinkerwell)
repeatedly show `empty` > `count` > `=== []`, but the margin is small and not worth the micro-optimizations.
Note: Same results (with `$n = 10000000`) for PHP v7.4.33 using onlinephp(dot)io sandbox tool.
<?php
$test = range(0, 1000);
$test2 = [];
$n = 1000_000_000;
$t1 = microtime(true); for ($x = 0; $x < $n; $x++) if (count($test)) {}
$t2 = microtime(true); for ($x = 0; $x < $n; $x++) if (count($test2)) {}
$t3 = microtime(true); for ($x = 0; $x < $n; $x++) if ($test === []) {}
$t4 = microtime(true); for ($x = 0; $x < $n; $x++) if ($test2 === []) {}
$t5 = microtime(true); for ($x = 0; $x < $n; $x++) if (empty($test)) {}
$t6 = microtime(true); for ($x = 0; $x < $n; $x++) if (empty($test2)) {}
$t7 = microtime(true);
echo "count(\$test): " . ($t2 - $t1) . " sec\n";
echo "count(\$test2): " . ($t3 - $t2) . " sec\n";
echo "\$test === []: " . ($t4 - $t3) . " sec\n";
echo "\$test2 === []: " . ($t5 - $t4) . " sec\n";
echo "empty(\$test): " . ($t6 - $t5) . " sec\n";
echo "empty(\$test2): " . ($t7 - $t6) . " sec\n";
?>
Results:
<?php
count($test): 18.034885168076 sec
count($test2): 17.133869886398 sec
$test === []: 20.059770107269 sec
$test2 === []: 14.204195022583 sec
empty($test): 13.583840847015 sec
empty($test2): 12.971315145493 sec
?>