Created
September 12, 2017 08:42
-
-
Save kuntalchandra/c1d7a88e54e5893b64ad74a125320764 to your computer and use it in GitHub Desktop.
Why if/else block should be avoided in loop, if possible.
This file contains hidden or 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 | |
$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