471,851 Members | 1,049 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,851 software developers and data experts.

for vs. while – which is faster?

8,658 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 3036
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,658 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
reply views Thread by NeoPa | last post: by
reply views Thread by YellowAndGreen | last post: by
reply views Thread by aboka | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.