Skip to content

Instantly share code, notes, and snippets.

@craigvantonder
Last active March 6, 2018 08:03
Show Gist options
  • Save craigvantonder/61d5e796e90e45ebaf8b60555a2dcb21 to your computer and use it in GitHub Desktop.
Save craigvantonder/61d5e796e90e45ebaf8b60555a2dcb21 to your computer and use it in GitHub Desktop.
Test execution times of for and foreach in PHP
<?php
// Create fake data array of 10000 records
$max = 10000;
$rands = array();
for($i=0; $i<$max;$i++) {
$rands[$i]=mt_rand(0,$max-1);
}
$temp;
// Time foreach itteration
$start = microtime(true);
foreach($rands as $rand) {
$temp = $rand * $rand;
}
echo 'Foreach: '.(microtime(true) - $start);
echo nl2br ("\n");
// Time for itteration
$start = microtime(true);
for($i=0;$i<count($rands);$i++) {
$temp = $rands[$i] * $rands[$i];
}
echo 'For: '.(microtime(true) - $start);
// Foreach: 0.00038695335388184
// For: 0.0019509792327881
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment