Haim Evgi
Haim Evgi

Reputation: 125614

Loop Code Optimization

How can I optimize the following code ,

I Need to run 3 sets of loops like this:

for($i=1;$i<=$count-1;$i++){    
  for($j=$i+1;$j<=$count;$j++){
  // do some query use $i and $j

  }
}
for($i=1;$i<=$count-2;$i++){
   for($j=$i+1;$j<=$count-1;$j++){   
     for($k=$j+1;$k<=$count;$k++){
       // do some query use $i and $j and $k
     }
  }
}
for($i=1;$i<=$count-3;$i++){
   for($j=$i+1;$j<=$count-2;$j++){   
      for($k=$j+1;$k<=$count-1;$k++){
     for($l=$k+1;$l<=$count;$l++){ 
       // do some query use $i and $j and $k and $l
       }
     }
  }
}

Is there a way to simplify the code, perhaps to connect the loops together ?

thanks !

Upvotes: 3

Views: 1175

Answers (3)

strager
strager

Reputation: 90062

This should do it (untested):

for($i = 1; $i <= $count - 3; $i++) {
    for($j = $i + 1; $j <= $count; $j++) {
        // i,j query

        if($j > $count - 2) {
            continue;
        }

        for($k = $j + 1; $k <= $count; $k++) {
            // i,j,k query

            if($k > $count - 1) {
                continue;
            }

            for($l = $k + 1; $l <= $count; $l++) {
                // i,j,k,l query
            }
        }
    }
}

Note that the queries are no longer in their original order.

As it has been said, there's no way to optimize this further without knowing the queries you are running.

Upvotes: 2

Mark Baker
Mark Baker

Reputation: 212522

Micro-optimization: Use

++$i

rather than

$i++

and equivalent for $j++, $k++ and $l++

But what are you doing in these loops: it's entirely possible that your do some query (database?) could be changed to remove the loops completely... and that would be far more effective than any micro-optimisations

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799390

The big problem is that the inner loops are run multiple times. You can get around this by checking i === 1 and j === 2 inside the loops and only running the appropriate code if true.

Upvotes: 1

Related Questions