Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Created October 19, 2020 12:06
Show Gist options
  • Save kobus1998/52f5de4b1d04b8d913d38f05587c64aa to your computer and use it in GitHub Desktop.
Save kobus1998/52f5de4b1d04b8d913d38f05587c64aa to your computer and use it in GitHub Desktop.
this tests the performance of count inside the loop or outside of the loop
<?php
function test1($arr)
{
$arr = array_fill(0, 10000, true);
$start = microtime();
for ($i = 0; $i < count($arr); $i++) {
array_fill(0, 500, "abc");
}
return ((float) microtime() - (float) $start);
}
function test2($arr)
{
$start = microtime();
$iCount = count($arr);
for ($i = 0; $i < $iCount; $i++) {
array_fill(0, 500, "abc");
}
return ((float) microtime() - (float) $start);
}
$iTries = 10;
$aResult1 = [];
$aResult2 = [];
$arr = array_fill(0, 100, true);
for($i = 0; $i < $iTries; $i++) {
$aResult1[] = test1($arr);
$aResult2[] = test2($arr);
}
echo "with count: " . round(array_sum($aResult1) / count($aResult1), 5) . "\n";
echo "without count: " . round(array_sum($aResult2) / count($aResult2), 5) . "\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment