this is wrinkling my brain. why is it faster?
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!