Loop code optimization

How can I optimize the following code,

I need to run three sets of loops, for example:

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 link the loops together?

thank!

+3
source share
3 answers

Micro Optimization: Use

++$i

but not

$i++

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

But what do you do in these loops: it is possible that your query (database?) Could be changed to completely remove the loops ... and that would be much more efficient than any micro-optimizations

0
source

This should do it (unchecked):

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 queries are no longer in the original order.

, , , .

+2

The big problem is that the inner loops run several times. You can work around this by checking i === 1and j === 2within cycles and performing only the appropriate code, if true.

+1
source

Source: https://habr.com/ru/post/1753279/


All Articles