Hacker News new | ask | show | jobs
by nostrademons 4516 days ago
The speed difference between querySelectorAll and getElementsBy* is entirely because of the difference between live nodelists and static nodelists. getElementsBy* returns a nodelist that reflects changes in the DOM in real time - this means that it's just returning a pointer. querySelectorAll copies the full result set into an array-like object at method-call time.

The flip side of this is that iterating over a querySelectorAll nodelist is significantly faster than iterating over a getElementsBy* nodelist. You really don't want to call .length on a getElementsBy* nodelist, because it's O(N) and has to traverse the full nodelist. .length on a querySelectorAll nodelist is just a field lookup. That means that when you combine the original call with one iteration, you're usually about breaking even with querySelectorAll.

Also, setting CSS properties doesn't for a full relayout; it just sets a dirty bit and the property. Setting CSS properties and then querying the DOM causes a full relayout. Unfortunately JQuery often does the latter in .css, which makes it slow as molasses. You can do direct .style manipulations all you want with very little performance penalty though.