Cutting down on loop iterations with labels

Just a quick reminder that you can drastically cut down on loop iterations by using the break and continue commands, and that there is an option to label loops to allow nested loops to stop their parents from iterating.

The Muffin Man Stuart Colville asked me earlier today how supported labels are in loops and breaks and I was confused at first as I had not heard or - more likely - forgotten about that feature.

Normally you have a loop and you go through it:


for(i=0; i<200; i++){
  if ( i==10 ) {
    alert ('10');
  }
}

This would execute 200 times. If you use a break, it only executes 10 times:


for(i=0; i<200; i++){
  if ( i==10 ) {
    alert ('10');
    break;
  }
}

If you have to nest loops though, the break would only stop the inner loop. The following example would still execute 2200 times:


for(i=0; i<200; i++){
  for(j=0; j<200; j++){
    if ( j==10 ) {
      alert ('10');
      break;
    }
  }
}

Now, the loop can get a label, which is a word followed by a colon, and that can be used to break or continue different loops. The following example only executes 11 times.


outer:for(i=0; i<200; i++){
  for(j=0; j<200; j++){
    if ( j==10 ) {
      alert ('10');
      break outer;
    }
  }
}

Using labels can help immensely on cutting down on loop iterations - and make scripts faster. Say for example you have a JSON object that is a search result:


  results={
    'CSS':{
      books:[
        {
          'title':'Bulletproof CSS',
          'author':'Dan Cederholm'
        },
        {
          'title':'Professional CSS',
          'author':'Various'
        },
        {
          'title':'Eric Meyer On CSS',
          'author':'Eric Meyer'
        }
      ],
      web:[
        {
          'title':'CSS discuss',
          'maintainer':'Eric Meyer'
        },
        {
          'title':'Simplebits',
          'author':'Dan Cederholm'
        },
        {
          'title':'456 Berea Street',
          'author':'Roger Johannson'
        }
      ]
    },
    ‘JavaScript’:{
      books:[
        {
          'title':'DOM Scripting',
          'author':'Jeremy Keith'
        },
        {
          'title':'Beginning JavaScript with DOM scripting and AJAX',
          'author':'Christian Heilmann'
        },
        {
          'title':'JavaScript:The Definitive Guide',
          'author':'David Flanagan'
        }
      ]
    }
  }

If you send the author and the media as query data, for example “Roger Johannson” and “web” you can use a normal nested loop:


   for(i in results){
      for(var j in results[i]){
        for(var k in results[i][j]){
          if(results[i][j][k]['author']==author){
            alert(results[i][j][k]['title']);
          }
        }
      }
    }

This would be executed 9 times. If you use a break, you can cut it down to 8 times.


    for(i in results){
      for(j in results[i]){
        for(k in results[i][j]){
          if(results[i][j][k]['author']==author){
            alert(results[i][j][k]['title']);
            break;
          }
        }
      }
    }

If you use a label on the main loop - for example “lookup” - and break the parent loop instead of the innermost one, it is 5 iterations.


    lookup:for(i in results){
      for(j in results[i]){
        for(k in results[i][j]){
          if(results[i][j][k]['author']==author){
            alert(results[i][j][k]['title']);
            break lookup;
          }
        }
      }
    }

If you also test for the media and continue that loop the whole construct will execute 2 times.


    lookup:for(i in results){
      media:for(j in results[i]){
        for(k in results[i][j]){
          if(j!=media) continue media;
          if(results[i][j][k]['author']==author){
            alert(results[i][j][k]['title']);
            break lookup;
          }
        }
      }
    }

You can see all the functions and results on the demo page .

Of course, another option would be to not break the loop, but put the lot in an own function/method and return to the main script with the result. However, this technique can collect several results before commencing with the rest of the functionality.

Again, thanks to Stuart for bringing that up. Other resources:

10 Responses to “Cutting down on loop iterations with labels”

  1. Jared Smith Says:

    Now how is it that I’ve never seen this before? You just saved my poor computer about a million loop iterations per day with my Greasemonkey scripts alone.

  2. getElementsByClassName Deluxe Edition | Muffin Research Labs Says:

    [...] I used a loop label which enabled the break statement to break out of two loops in one go. For more information on Loop labels Chris Heilmann knocked up this little post after I asked him about [...]

  3. getElementsByClassName Deluxe Edition | Muffin Research Labs Says:

    [...] I used a loop label which enabled the break statement to break out of two loops in one go. For more information on Loop labels Chris Heilmann knocked up this little post after I asked him about [...]

  4. Robin Says:

    Oh, excellent! Great tip

  5. Jeff L Says:

    Great article - however you never answered the first question about how supported they are.

    Also, it would be great if you would write about “break”s friend, “continue” - another way to help make your loops more friendly.

  6. Jordi Pujalte Says:

    I tested it to work on IE4+, so I suppose it should work on anything that supports JS.

  7. lifemachine Says:

    How is that different from putting the whole thing in a function and doing using a return?

  8. frequency decoder Says:

    Nice post, I’ve just shown it to the other developers at work to combined sounds of ‘Ohhhh’ (read the ‘Ohhh’ in a French accent to really set the scene).

    Nice post - concise but nice.

    Regards,
    Brian

  9. Templaterie Blog Says:

    [...] jedem Fall ist es ein Gedanke Wert, das Maß separat in einer Variable zu deklarieren. Loops und der Ausstieg aus derselben, sobald klar ist, dass nicht weiter dieser Loop (=Schleife) gebra [...]

  10. Useful Utility Functions in mootools | CoryHudson.com Says:

    [...] ents. What, you’re not using break and continue statements? They can really help you cut down on loop iterations. There is no way to use break or continue in an each loop in mootools, so [...]

Leave a Reply

@mediaAjax
Wait till I come! is the blog of , a developer evangelist living and working in London, England. Download vcard.

Feed me, Seymour: Entries (RSS) and Comments (RSS).