开发者

Loop Code Optimization

开发者 https://www.devze.com 2023-01-06 01:03 出处:网络
How can I optimize the following code , I Need to run 3 sets of loops like this: for($i=1;$i<=$count-1;$i++){

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

  }开发者_JAVA技巧
}
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 !


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.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消