I have seen Javascript code that claims to speed up function call overhead like:
function foo() {
// do something
}
function myFunc() {
var fastFoo = foo; // this caches function foo locally for faster lookups
for (var i = 0; i < 1000; i++) {
fastFoo();
}
}
I do not see how this can speed up javascript function call overhead, as it seems to me like it is just a memory lookup, either at the top of the current stack (for fastFoo) or somewhere else in the stack (I am not sure where the global context is stored… anyone?).
Is this a relic of ancient browsers, a complete myth, or a true improvement enhancer?
It is all dependent on scope. Accessing the local scope is always faster than accessing a parent scope. if the function is defined in the parent scope you will often see speedups if you make a local reference.
If this speedup is significant depends on many things, and only testing in your case will show if it is worth doing so.
The difference in speed depends on the difference of scope.
Calling
a.b.c.d.e.f.g.h();from the scope ofx.y.zis slower than callinga.b();from the scope ofa.b.c(not the prettiest or most correct examples, but it should ´serve it’s purpose 🙂