Friday, April 30, 2010

When does Nesting Loops become a Bad Practice?

Let's face it, nested loops are indispensable for complex algorithms to compute n-digit counters, factorials, permutations, multi-threading and a lot more. But before we do so, let's rethink our implementation and see if there are other alternatives.

With this argument, nested loops are not necessarily a bad thing. They become a bad practice when a well known alternative is there and you don't use it. Instead, you stick to your implementation without being wary of how it would affect your application especially if it's an area with high user demand.

Let's take a look at the following example.
Nested Loop:
$elements_to_check_from = array(1,2,3,4,5,6,7,8,9,10);
$elements_to_check = array(1,2,3,4,5,6,7,8);
function nested($elements_to_check, $elements_to_check) {
foreach($elements_to_check as $el){
foreach($elements_to_check_from as $el2) {
if($el2 == $el) {
return true;
}
}
}
}

Wherein, it's possible to avoid it by implementing a hash key lookup. Then verifying if it's there. This will save you tons of computing resources if one, it's a process that you use all the time and two, if your lookup data doesn't change that much.
Not Nested Loop:
$elements_to_check_from[1] = 1;
$elements_to_check_from[2] = 1;
$elements_to_check_from[3] = 1;
$elements_to_check_from[4] = 1;
$elements_to_check_from[5] = 1;
$elements_to_check_from[6] = 1;
$elements_to_check_from[7] = 1;
$elements_to_check_from[8] = 1;
$elements_to_check_from[9] = 1;
$elements_to_check_from[10] = 1;

$elements_to_check = array(1,2,3,4,5,6,7,8);

function notnested($elements_to_check, $elements_to_check) {
foreach($elements_to_check as $el){
if (isset( $elements_to_check [$el])) {
return true;
}
}
}
  • Related Links Widget for Blogspot

No comments: