Created
March 26, 2024 13:51
-
-
Save joachim-n/a75ceed3186d63dc2a13e66bc799596d to your computer and use it in GitHub Desktop.
inline call for loop list vs variable assignment
This file contains 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 | |
// 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