Skip to content

Instantly share code, notes, and snippets.

@jonathanlaf
Last active September 26, 2018 19:19
Show Gist options
  • Save jonathanlaf/f973d9cb5448e362a2bd4217c1d46873 to your computer and use it in GitHub Desktop.
Save jonathanlaf/f973d9cb5448e362a2bd4217c1d46873 to your computer and use it in GitHub Desktop.
[Benchmark Loops] Benchmark of FOR vs FOREACH loop functions in php #php #benchmark
<?php
$a = array();
for ($i = 0; $i < 100000; $i++) {
$a[] = $i;
}
$start = microtime(true);
foreach ($a as $k => $v) {
$a[$k] = $v + 1;
}
echo "1- Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {
$v = $v + 1;
}
echo "2- Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => $v) {}
echo "3- Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
foreach ($a as $k => &$v) {}
echo "4- Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
$countFor = count($a);
for ($i=0;$i<$countFor;$i++) {
$a[$i] = $a[$i]+1;
}
echo "5- Completed in ", microtime(true) - $start, " Seconds\n";
$start = microtime(true);
$countFor = count($a);
for ($i=0;$i<=$countFor;$i++) {}
echo "6- Completed in ", microtime(true) - $start, " Seconds\n";
@DarckBlezzer
Copy link

DarckBlezzer commented Sep 26, 2018

$start = microtime(true);
$countFor = count($a);
for ($i=0;$i<=$countFor;$i = $i+1) {}
echo "7- Completed in ", microtime(true) - $start, " Seconds\n";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment