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!
> Was anyone else surprised by the performance penalty of jQuery? Over 400x hit for getElementsByTagName!
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.
I suspect the benchmark is flawed, and charging jQuery for one-time penalties for every function. i.e., if you make a page that has nothing but a getElementById call, vs. loading jQuery and executing the query on the DOM, it's obviously going to be a lot slower. Even if that's not the case, "fast enough" is fast enough...and jQuery has proven itself to be fast enough for a lot of stuff. And, most developers working in JavaScript and building their own helper libraries and such are extremely likely to make worse libraries than jQuery. So, it's probably smarter to use a library that's getting a lot of vetting by really smart people. Whether it's jQuery or something else, I'm not gonna go back to hand-written JavaScript (I'm in the midst of converting an app to use jQuery from handwritten functions, and the new version is either faster or similarly fast, and maintenance of the frontend is getting vastly simpler with every element that gets converted from the handwritten functions to jQuery+Bootstrap...hell, sometimes, I'm able to just use markup with no JavaScript on the page at all...and that's like magic).