How to write up to 98% faster JavaScript code.
jsperf.com
jsperf.com
Moral of the story? Perhaps, "make local aliases for objects used in performance-critical loops." Nothing new here.
Certainly not a good argument for one style of JavaScript library over the other (which seems to be the aim).
Sad to see this kind of silliness on HN.
nevertheless it shows that if you don't keep those rules in mind all the time you might end up with very slow code.
Thanks for your comment though!
As I said; it's either deliberately misleading--or the author's understanding of javascript is too limited as to be making claims that "jQuery and other libraries could have been 98% faster." A comment, by the way, which was later modified to state "if you are not a JavaScript Ninja your framework code could have been up to 98% faster."
Sorry, I don't file that knowledge under "Javascript Ninja" knowledge--and moreover, the original comment was designed to say, "My library is faster / better than all of these popular libraries."
[Edit] To my (admittedly cynical at times) that adds up to deliberately misleading.
http://jsperf.com/global-namespace-chain-vs-string-based-loc...
In your tests the method "add" is pretty far away from it's original variable, and MUCH further away than any jQuery method is, so you're also testing the time it takes to lookup that method. In jQuery, methods are either attached to "jQuery" directly or on the prototype.
As other people have mentioned, here we see identical perf when moving the add function lookup out of the inner loop.
window.Library = {};
window.Library.util = {};
window.Library.util.add = function(a, b) {
return a + b;
};
var add = window.Library.util.add;
Then you will find that: add();
Will be faster than: window.Library.util.add()
It's unfortunate that JavaScript interpreters can't do something to fix this. Maybe Google's V8 JIT can speed this situation up. window.Library.util.add()
To: var window_Library_util_add = window.Library.util.add;
window_Library_util_add(); int len = array.length
for(i = 0; i < len; i++){
}
vs. for(i = 0; i < array.length; i++){
}
The code is semantically different and therefore has a different performance profile.I'm not sure if v8 does any whole-module optimisations... if it does, then there's got to be loads of "invalidate me" hooks everywhere. I doubt it would be worth doing, but if anyone has more precise info - please correct me :)
It's not particularly expensive, but if you do it in a tight loop 100k times it'll look slow compared to something that doesn't need to do that work.
As others have said, the trick is simply to perform those lookups earlier and assign the resulting function/data to a variable.
I have no idea how boring and where dynamic web-paging would be today without JS!