for vs. while – which is faster?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    for vs. while – which is faster?

    out of curiosity, does anyone know, if a for-loop or a while-loop executes faster?

    ex.
    Code:
    var elements = document.getElementsByName("name");
    
    for (var i = 0, l = elements.length; i < l; i++)
    {
        // some code with [I]elements&#91;i][/I]
    }
    
    var elem, i = 0;
    while (elem = elements[i])
    {
        // some code with [I]elem[/I]
        i++;
    }
  • mrhoo
    Contributor
    • Jun 2006
    • 428

    #2
    while (elem = elements[i]) may not mean what you thought.
    Code:
    var elements= document.getElementsByName("name"), 
    L= elements.length;
    while(L){
    	elem= elements[--L];
    	//do something
    }

    Comment

    • Dormilich
      Recognized Expert Expert
      • Aug 2008
      • 8694

      #3
      Originally posted by mrhoo
      while (elem = elements[i]) may not mean what you thought.
      why should I not mean it like that? I've tested the code (works) and I can be sure the element really exists. furthermore, I don't have to access the array/HTMLCollection in the loop.

      I could even go as far as (works too)
      Code:
      while (elem = elements[i++]) {}

      Comment

      • mrhoo
        Contributor
        • Jun 2006
        • 428

        #4
        It depends on what you are doing with the elements.

        Nodelists are live- if you start with the last element, and count down in the while loop, you can remove some of them safely. If you increment by one and remove an element, you'll skip the next one. Counting down is safer with nodelists.

        Comment

        Working...