469,357 Members | 1,914 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,357 developers. It's quick & easy.

for vs. while which is faster?

8,652 Expert Mod 8TB
out of curiosity, does anyone know, if a for-loop or a while-loop executes faster?

Expand|Select|Wrap|Line Numbers
  1. var elements = document.getElementsByName("name");
  3. for (var i = 0, l = elements.length; i < l; i++)
  4. {
  5.     // some code with elements[i]
  6. }
  8. var elem, i = 0;
  9. while (elem = elements[i])
  10. {
  11.     // some code with elem
  12.     i++;
  13. }
Apr 8 '09 #1
3 3013
428 256MB
while (elem = elements[i]) may not mean what you thought.
Expand|Select|Wrap|Line Numbers
  1. var elements= document.getElementsByName("name"), 
  2. L= elements.length;
  3. while(L){
  4.     elem= elements[--L];
  5.     //do something
  6. }
Apr 8 '09 #2
8,652 Expert Mod 8TB
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)
Expand|Select|Wrap|Line Numbers
  1. while (elem = elements[i++]) {}
Apr 8 '09 #3
428 256MB
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.
Apr 9 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

36 posts views Thread by Armin Rigo | last post: by
23 posts views Thread by YinTat | last post: by
1 post views Thread by James dean | last post: by
12 posts views Thread by karthikbalaguru | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.