|
|
|
|
|
by paulrosenzweig
5039 days ago
|
|
Was anyone else surprised by the performance penalty of jQuery? Over 400x hit for getElementsByTagName! I'm curious whether this is more due to cross browser checks or determining the what type of selector was used. To the source! |
|
Not really. Just replacing document.getElementsByTagName by document.querySelectorAll (the native, browser-implemented version of what jQuery does) will generate a 150-200x perf hit depending on the browser.
The reason for that is twofold: first, getElementsByTagName doesn't have to parse the selector, figure out what is asked for, and potentially fall back on explicit JS implementation (jQuery supports non-native selectors. In fact, I believe you can implement your own selectors). But the parsing overhead should be minor in this precise case.
Second, the real reason for the difference, getElementsByTagName cheats something fierce: it doesn't return an Array like everybody else, it returns a NodeList. And the nodelist is lazy, it won't do anything before it needs to. Essentially, just calling document.getElementsByTagName is the same as calling an empty function. If you serialize the nodelist to an array (using Array.prototype.slice.call), bam 150~200x perf hit.
See http://jsperf.com/vanillajs-by-tag/2 for these two alterations added to the original "vanilla JS" perf cases.
There is a significant overhead to jQuery, but it's ~3x compared to the equivalent DOM behavior, not 400x.