Created
October 6, 2024 19:01
-
-
Save theodorejb/9b2beee8c278d98caa6dad98ef1963ef to your computer and use it in GitHub Desktop.
Fastest way to check for an empty PHP array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$empty = []; | |
$uniform = []; | |
$integer = []; | |
$string = []; | |
$mixed = []; | |
$assoc = []; | |
for ($i = 0; $i < 500000; $i++) { | |
$iMd5 = md5((string) $i); | |
$uniform[] = 0; | |
$integer[] = $i; | |
$string[] = $iMd5; | |
$mixed[] = $i % 2 ? $i : $iMd5; | |
$assoc[$iMd5] = $i; | |
} | |
$results = [ | |
'Empty' => getTimes($empty), | |
'Uniform' => getTimes($uniform), | |
'Integer' => getTimes($integer), | |
'String' => getTimes($string), | |
'Mixed' => getTimes($mixed), | |
'Associative' => getTimes($assoc), | |
]; | |
$totals = []; | |
for ($i = 0; $i < 4; $i++) { | |
$total = 0.0; | |
foreach ($results as $result) { | |
$total += $result[$i]; | |
} | |
$totals[] = $total; | |
} | |
echo " | count | empty | === [] | cast |\n"; | |
echo "-------------|--------------|--------------|--------------|--------------|\n"; | |
foreach ($results as $name => $times) { | |
echo getTitleCol($name) . formatTimes($times); | |
} | |
echo "-------------|--------------|--------------|--------------|--------------|\n"; | |
echo getTitleCol('Total') . formatTimes($totals); | |
/** | |
* @return array{float, float, float, float} | |
*/ | |
function getTimes(array $arr): array | |
{ | |
$nt = 90000000; | |
$t0 = microtime(true); | |
for ($i = 0; $i < $nt; $i++) { | |
count($arr) === 0; | |
} | |
$t1 = microtime(true); | |
for ($i = 0; $i < $nt; $i++) { | |
empty($arr); | |
} | |
$t2 = microtime(true); | |
for ($i = 0; $i < $nt; $i++) { | |
$arr === []; | |
} | |
$t3 = microtime(true); | |
for ($i = 0; $i < $nt; $i++) { | |
!$arr; | |
} | |
$t4 = microtime(true); | |
return [$t1 - $t0, $t2 - $t1, $t3 - $t2, $t4 - $t3]; | |
} | |
function getTitleCol(string $title): string | |
{ | |
return str_pad($title, 12, ' ', STR_PAD_LEFT) . ' |'; | |
} | |
/** | |
* @param non-empty-list<float> $times | |
*/ | |
function formatTimes(array $times): string | |
{ | |
$minIndex = array_keys($times, min($times))[0]; | |
$formatted = []; | |
foreach ($times as $i => $time) { | |
$str = number_format($time, 6); | |
if ($i === $minIndex) { | |
$formatted[] = " * $str "; // if fastest put star before number | |
} else { | |
$formatted[] = " $str "; | |
} | |
} | |
return implode('|', $formatted) . "|\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment