How much looping is too much? (PHP Do-While Loop)

There may not really be an answer to this, but I'm wondering how much is too much when it comes to do-while loops.

For example, if it has to loop through 10 times, is that considered bad? 5 times? Does it depend on the kinds of things the loop is doing? Would there be a way to track the amount of "effort" (memory?) it's taking to execute the loop and use that to determine if it's ok or not?

This is more of an open-ended "discussion" as opposed to me looking or a specific answer.

Answers


For individual loops it really depends on what the code inside is doing, if it's taking too long to compute, or eating up piles of memory then you have to find that bit and change it. Realistically there's no upper limit on how many iterations a "good loop" does because it's "however many are necessary".

The real snag that's very easy to fall into is nested loops. eg:

for( $i=0; $i<100; $i++ ) {
    for( $j=0; $j<100; $j++ ) {
        for( $k=0; $k<100; $k++ ) {
             // some code       
        }
    }
}

It looks innocuous, but the code in the inner loop will be evaluated 1,000,000 times. Optimizing code like this for sorting/searching/etc isn't just an 'open-ended discussion' it's a vast portion of all Computer Science.


Need Your Help

Set non text content to DOM Element in Android

android string dom document

I read a html template from assets and want to add html into a certain div.

How do you order by Greatest number in linq

c# linq

I would like to print products in order of quantity.The product with a bigger total should be first.