3 ms·
As ehynds (above) pointed out, the example could have been drastically simplified down to: window.Library = {}; window.Library.util = {}; window.Library.
by dstein 16y ago
As ehynds (above) pointed out, the example could have been drastically simplified down to:
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.
- viraptor 16y agoI'm not sure it would be legal to fix up automatically. What is expected if you have a background timer which could change "window.Library.util" at some point? If you resolve every time, you'll get a new "add()", if you cache, you'll get the same.
- dstein 16y agoYou're right maybe it can't be done universally. But you could add an optimizer to a production build system which rewrites any instance of: window.Library.util.add() To: var window_Library_util_add = window.Library.util.add; window_Library_util_add();
- reeses 16y agoAre you saying that the V8 JIT won't catch this? What if it optimizes _any_ function/module/etc. that is later changed? The optimization should be discarded when the reference is reassigned. If it's not, then V8 has a bug that should be manifesting everywhere.
- fleitz 16y agoThe problem is that the code is not semantically identical, there is no way for the compiler to know that nothing else has changed while the loop is executing. It's like the frequent optimization case of 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.
- viraptor 16y agoDepends what you mean by "changed". The function body itself cannot change in javascript afaik. The function bound to some name can change, but that's equivalent to the name pointing at another structure. The new structure will have its own compiled version of the new function. It doesn't mean though that it can just fold multiple resolutions of the same name into a local variable and cache it. This kind of behaviour would be similar to optimising random() to return 4. 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 :)