Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better practice - for loop with break or conditional loop? [closed]

I'm just curious what peoples' thoughts are on this topic. Let's say I have an Array of Objects, and I want to loop through them to see if the Objects contain certain values, and if so, I want to stop the loop. Which is better practice - a for loop with a break, or a conditional loop?

The pseudo-code in the example I have provided is for argument's sake only (it is also in ActionScript, since that is my primary language of late). Also, I am not looking for best practice ideas on syntax.

for loop with break:

var i:int;  var isBaxterInMilwaukee:Boolean;      for (i = 0; i < arrayLen; i++) {     if (myArray[i]["name"] == "baxter"          && myArray[i]["location"] == "milwaukee")     {         isBaxterInMilwaukee = true;          barkTwice();          break;     } } 

conditional loop:

var i:int;  var isBaxterInMilwaukee:Boolean;      while (!isBaxterInMilwaukee && i < arrayLen) {     if (myArray[i]["name"] == "baxter"          && myArray[i]["location"] == "milwaukee")     {         isBaxterInMilwaukee = true;          barkTwice();     }      i++; } 
like image 764
Eric Belair Avatar asked Feb 27 '09 17:02

Eric Belair


People also ask

Which type of loop is most effective one?

The for loop is probably the most common and well known type of loop in any programming language. For can be used to iterate through the elements of an array: For can also be used to perform a fixed number of iterations: By default the increment is one.

Which situation work best with a for loop?

In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.

Which is best loop for or while?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.

Which loop works fastest?

The traditional for loop is the fastest, so you should always use that right? Not so fast — performance is not the only thing that matters. It is rare that you will ever need to loop over 1 million items in a frontend JS app.


1 Answers

In short, you should go with whichever version is the easiest to read and maintain.

In slightly older times, I know breaking out of a loop was considered to be a no-no (on par with a goto statement). Loops were supposed to break on the loop condition and nowhere else. Thus, the while-loop would have been the way to go.

(This is probably a holdover from assembly, where loops are basically a block of code with a go-to-the-beginning-if-true jump statement at the end. Multiple conditional-jump statements in the block make it exceedingly hard to debug; thus they were to be avoided and combined into one at the end.)

I feel this idea seems to be changing a bit today, especially with foreach loops and the managed world; it's really a matter of style now. Break-on-found for-loops have perhaps come to be acceptable to many, save some purists of course. Note that I would still avoid using break in a while-loop, however, as this can muddle the loop condition and make it confusing.

If you'll allow me to use a foreach loop, I consider the code below to be a lot easier to read than its while-loop brother:

bool isBaxterInMilwaukee;      foreach (var item in myArray) {     if (item.name == "baxter" && item.location == "milwaukee")     {         isBaxterInMilwaukee = true;             barkTwice();         break;     } } 

However, as the logic grows in complexity, you may want to consider a prominent comment near the break statement lest it become buried and hard to find.


Arguably, this whole thing should be refactored into its own function which doesn't break on found, but actually returns the result (feel free to use the for-loop version instead):

bool isBaxterInMilwaukee(Array myArray) {           foreach (var item in myArray)     {         if (item.name == "baxter" && item.location == "milwaukee")         {             barkTwice();             return true;         }     }     return false; } 

As Esko Luontola pointed out, it would probably be best to move the call to barkTwice() outside of this function as the side-effect is not evident from the function's name, nor related to finding Baxter in every case. (Or add a boolean parameter BarkTwiceIfFound and change the line to read if(BarkTwiceIfFound) barkTwice(); to make the side-effect clear.)


For the record, you can also do the flag check in the for-loop without a break, but I feel this actually hurts readability because you don't expect an extra condition in a for-loop definition:

var i:int;  var isBaxterInMilwaukee:Boolean;      for (i = 0; !isBaxterInMilwaukee && i < arrayLen; i++) {     if (myArray[i]["name"] == "baxter"          && myArray[i]["location"] == "milwaukee")     {         isBaxterInMilwaukee = true;             barkTwice();     } } 

You can also simulate auto-incrementing mechanics with a while-loop. I don't like this for a few reasons - you have to initialize i to be one less than your real starting value, and depending on how your compiler short-circuits the loop-condition logic, your value of i on exiting the loop may vary. Nevertheless, it is possible and for some people, this can improve readability:

var i:int = -1;  var isBaxterInMilwaukee:Boolean;      while (!isBaxterInMilwaukee && ++i < arrayLen) {     if (myArray[i]["name"] == "baxter"          && myArray[i]["location"] == "milwaukee")     {         isBaxterInMilwaukee = true;         barkTwice();     } } 
like image 180
lc. Avatar answered Sep 26 '22 02:09

lc.