Monday, April 10th, 2006

Faster DOM Queries

Category: Editorial, JavaScript

Dean Edwards and Alex Russell have been noodling on how to speed up DOM work.

Alex started this off with a “janky hack” that uses our favourite document.getElementById in a naughty way, by grouping elements by one id. His hack includes a cached element version.

Dean grimaced at the non-standardiness of it, but knows that we need faster DOM work. He played with XPath as a solution and his work concluded:

  • DOM queries on Firefox seem pretty quick
  • XPath is about 150% faster than DOM queries on a Mozilla platform
  • XPath is about 1000% faster than DOM queries on an Opera platform
  • the expression hack is about 200-400% faster on an IE platform
  • Behaviour leaks like a sieve

Posted by Dion Almaer at 5:53 am

3.6 rating from 34 votes


Comments feed TrackBack URI

Hi all,

I really don’t think doing that (Alex’s) hack will make accessing elements with same id faster. The faster way is to use document.all. Most of the browsers implemented document.all now. Please check the fastness by yourself with the following link: .
Please click on the second button first as Alex’s method is resetting ids. I tested in IE 6, Firefox 1.5, opera 8.54 and in all these browsers document.all method took almost 0ms. I know it’s not a W3C standard but when all the browsers implemented that, I don;t see any other reason why we should stop using that.

Pavan Keely

Comment by Pavan Keely — April 10, 2006

I guess I don’t understand the big need for speed in this dept. Seems like if you have to do huge DOM queries on every page, maybe the app could use a redesign/optimization in general. XPath looks good, but you could also just have your server-side code spit out an array of IDs in a script element and loop over that with getElementById. Basically move the hassle of finding certain DOM elements onto the server’s shoulders where you’ve got plenty of speed.

Comment by Stephen Clay — April 10, 2006

Interesting Finds

Trackback by Jason Haley — April 11, 2006

Leave a comment

You must be logged in to post a comment.