Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Created September 12, 2017 08:42
Show Gist options
  • Save kuntalchandra/c1d7a88e54e5893b64ad74a125320764 to your computer and use it in GitHub Desktop.
Save kuntalchandra/c1d7a88e54e5893b64ad74a125320764 to your computer and use it in GitHub Desktop.
Why if/else block should be avoided in loop, if possible.
<?php
$sortedSet = range(1, 10000000);
$randomSet = $sortedSet;
shuffle($randomSet);
$cnt = count($sortedSet);
$filter = $cnt / 2;
$sortedSetChunks = array_chunk($sortedSet, $filter);
$randomSetChunks = array_chunk($randomSet, $filter);
//process random set by considering if/ else block within loop
$startTime = microtime(true);
processSet($randomSet, $filter);
$endTime = microtime(true);
echo "\nRandom set with if/ else block processed in " . ($endTime - $startTime) . " s\n";
//process random sets without any if else block in loop
$startTime = microtime(true);
foreach ($randomSetChunks as $randomSet) {
processBrokenSet($randomSet);
}
$endTime = microtime(true);
echo "\nSplit random sets processed in " . ($endTime - $startTime) . " s\n";
//process sorted set by considering if/ else block within loop
$startTime = microtime(true);
processSet($sortedSet, $filter);
$endTime = microtime(true);
echo "\nSorted set with if/ else block processed in " . ($endTime - $startTime) . " s\n";
//process sorted sets without any if else block in loop
$startTime = microtime(true);
foreach ($sortedSetChunks as $sortedSet) {
processBrokenSet($sortedSet);
}
$endTime = microtime(true);
echo "\nSplit sorted sets processed in " . ($endTime - $startTime) . " s\n";
function processSet(array $set, $filter)
{
$i = 0;
$sum = 0;
$sum1 = 0;
foreach ($set as $value) {
if ($i > $filter) {
$sum += $value;
} else {
$sum1 += $value;
}
$i++;
}
$total = ($sum + $sum1);
echo "Sum: $sum Sum1: $sum1 Total: $total";
return $total;
}
function processBrokenSet(array $set)
{
$sum = 0;
foreach ($set as $value) {
$sum += $value;
}
echo "Sum: $sum";
return $sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment