Skip to content

Instantly share code, notes, and snippets.

@joachim-n
Created March 26, 2024 13:51
Show Gist options
  • Save joachim-n/a75ceed3186d63dc2a13e66bc799596d to your computer and use it in GitHub Desktop.
Save joachim-n/a75ceed3186d63dc2a13e66bc799596d to your computer and use it in GitHub Desktop.
inline call for loop list vs variable assignment
<?php
// THIS DOESN'T WORK!
// SOME WEIRD INTERNAL CACHING IS HAPPENING - whichever is executed second
// is faster!
function getLoopList() {
return range(1, 10);
}
function slowVersion() {
// Slow version
$t1 = microtime(true);
$list = getLoopList();
foreach ($list as $item) {
$item ** $item;
}
$t2 = microtime(true);
echo "slow time: " . number_format($t2 - $t1, 20) . "\n";
return $t2 - $t1;
}
function optimisedVersion() {
// Optimized version
$t3 = microtime(true);
foreach (getLoopList() as $item) {
$item ** $item;
}
$t4 = microtime(true);
echo "fast time: " . number_format($t4 - $t3, 20) . "\n";
return $t4 - $t3;
}
optimisedVersion();
slowVersion();
// $speedup = round(100 * (($t2 - $t1) - ($t4 - $t3)) / ($t2 - $t1), 0);
// echo "speedup: {$speedup}%\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment