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 t
Implementations are free to do whatever they like, but since id is 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:
ID: 0.0082ms per lookup
Tag: 0.0249ms per lookup
So, dramatically faster by ID than tag name.
IE7 reports:
ID: 2.4438ms per lookup
Tag: 0.0437ms per lookup
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:
ID: 1.1335ms per lookup
Tag: 0.0287ms per lookup
So about the same as IE7.
Firefox 3.6.3 reports:
ID: 0.0042ms per lookup
Tag: 0.006ms per lookup
So it doesn't care that much (on repeated requests; again, it may be caching).
Opera 10.5.1 reports:
ID: 0.006ms per lookup
Tag: 1.467ms per lookup
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:
Test Page
test testtesttesttesttest
test testtesttesttesttest
test testtesttesttesttest
test testtesttesttesttest
test testtesttesttesttest
test testtesttesttesttest