Blog Stats
  • Posts - 19
  • Articles - 0
  • Comments - 7
  • Trackbacks - 9

 

JavaScript Performance: Fast DOM Iterator

After numerous tests, this function provides the most performant way to iterate over all the elements in the DOM:

function walkTheDom() {

      var items = document.getElementsByTagName("*");

      var i=items.length;

      var item;

      do

      {

        item = items[i];

        //Do something with item

      }

      while (--i);

}

 

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Feedback

# re: JavaScript Performance: Fast DOM Iterator

Gravatar Interesting... can you elaborate on the different methods you tested and the times they took? 3/3/2006 7:51 AM | Patrick Fitzgerald

# re: JavaScript Performance: Fast DOM Iterator

Gravatar Hey Patrick ... you can check out my test page here

http://michaelparsons.ca/javascriptperformance.htm
3/3/2006 8:32 AM | Mike Parsons

# re: JavaScript Performance: Fast DOM Iterator

Gravatar You got a bug in the code - the first item is out of range. It should read item = items[i-1];

Otherwise: Thanks! 3/9/2008 9:15 AM | Johannes

# re: JavaScript Performance: Fast DOM Iterator

Gravatar i--;
do {
item = items[i];
//Do something with item
}
while(i--);

also the expression in *while* must
be post-decrement instead,
otherwise you'll miss item[0].

cheers
2/26/2009 2:51 AM | Anonymous

# re: JavaScript Performance: Fast DOM Iterator

Gravatar i just understood how it works when applying the suggestion of Johannes. in his fix it must stay pre-increment:

do {
item = items[i-1];
//Do something with item

}
while(--i);
2/26/2009 2:57 AM | Anonymous

# re: JavaScript Performance: Fast DOM Iterator

Gravatar nice script and i think it's a little bit faster than normal flow. 5/24/2010 6:12 AM | Nirala

# clearer logic

Gravatar Thanks for doing these benchmarks! I believe the clearest way to write the reverse loop is

while (i--) {
item = items[i];
// Do something with item
} 10/23/2010 9:37 PM | Katherine

# re: JavaScript Performance: Fast DOM Iterator

Gravatar var i=items.length;
var item;
do
{
item = items[--i];
//Do something with item
}
while (i);

Though I wonder how much faster this'll be than a normal for loop. Could you post your test results? 2/16/2011 1:10 PM | Richard

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

 

 

Copyright © Michael Parsons