Does the DOM have a hash-table of elements whose keys are the elements’ ids?
I want to know if document.getElementById looks up a hash table or traverses the entire tree.
Is this behavior different across browsers?
Does the DOM have a hash-table of elements whose keys are the elements’ ids?
Share
Implementations are free to do whatever they like, but since
idis defined as a unique value, it would seem sensible to use a hash map or similiar lookup mechanism rather than traversal. What seems sensible from the outside, though, may not be when you get into the plumbing of building a complex web browser with many (sometimes conflicting) imperatives.I did an easy but very simplistic test (see page at end of answer). It’s very simplistic not least because we don’t know that browsers don’t cache previous results.
Chrome 4.1.249.1059 reports:
So, dramatically faster by ID than tag name.
IE7 reports:
So dramatically faster by tag name than ID (but remember IE7 has a broken concept of
getElementById; this is fixed in IE8).IE8 (on a different machine, don’t compare absolutes, we’re looking at diffs within the browser tested) reports:
So about the same as IE7.
Firefox 3.6.3 reports:
So it doesn’t care that much (on repeated requests; again, it may be caching).
Opera 10.5.1 reports:
Dramatically faster by ID than tag name.
Make of those results what you will. A more complex test case would be needed to really infer the mechanisms. Of course, in at least two of those cases (Firefox and Chrome), we can go look at the source. CMS kindly points us to the WebKit and Firefox implementations (and looking at it, my suspicion about caching may have been on the money).
Test page: