Hacker News new | ask | show | jobs
by enraged_camel 3021 days ago
In terms of pure CSS it doesn't matter, but for JavaScript that manipulates the DOM (e.g. jQuery), it does. Specifically, `getElementById` is more than 50% faster than `getElementsByClassName`.

https://jsperf.com/id-vs-class-hn/1

1 comments

That micro benchmark is comparing getElementById which is a map lookup (assuming the id is unique in the document) vs getElementsByClassName which is creating an iterator that would scan the document as you loop over it, except that the page is not looping over it or calling .length, so it's not really scanning anything at all.

Essentially it's benchmarking a handful of branches inside getElementById that do the map lookup for an Element [1] against the handful of branches inside getElementsByClassName that do the map lookup for a NodeList [2]. They both look pretty similar to me in branch and map lookup count, so I'm not sure where the difference is, but it's not something that would impact real content since on a real page getElementsByClassName's cost is related to typical behavior being O(N) instead of O(1) like getElementById. Browsers have a ton of caching around it though, so getElementsByClassName can look like O(1) in micro benchmarks.

You could could alter the benchmark to do getElementsByClassName("my-class")[0] to test the scanning but browsers cache that too, so you'd need to actually modify the document between each run of the benchmark somehow (ex. adding or removing an element) to invalidate the cache.

Typical content that uses getElementById will be faster than content that uses getElementsByClassName, but it's hard to show that in a benchmark. :)

[1] https://cs.chromium.org/chromium/src/third_party/WebKit/Sour...

[2] https://cs.chromium.org/chromium/src/third_party/WebKit/Sour...