Javascript use explicit self/window objects to improve performance
-
26-09-2019 - |
Question
I read on MSDN that to improve scripting efficiency, you can use self
to make implicit window references explicit.
Do you know if this is true? Does this basically mean that for instance calling
self.location
is somewhay more efficient than calling simplylocation
with nowindow
opject before?Since the MSDN text is referred to the
self
and notwindow
, does this performance increase happens only usingself
? According to herewindow
andself
andwindow.self
are the same thing, so it shouldn't matter what we use, i'm asking only to make sure.Moreover following what stated in MSDN calling
window.self
should be somehow more performant than callingself
because this last one is a property ofwindow
so by callingwindow.self
we use an explicit ref.
Thanks
Solution
Although it's very much a micro-optimization, direct property references are always faster than variable lookups. When you write location
, something like the following is performed:
- Look for
location
declared in the current scope, return and exit if found. - Go up the scope hierarchy by one.
- If scope is not Global, go to 1. If scope is Global, check for
location
in global scope and return if found, otherwise throw undeclared variable error.
A similar case is made against using the with
statement to create a scope for object properties. The same goes for self
, which is also a property of window
. self
is a reference to window
, so window.location
should be faster than window.self.location
. Also, remember that implementations can be different, so your mileage may vary from browser to browser.
As Pointy "pointied" out, most developers don't have to worry about micro-optimizations like this. The difference is micro-seconds and completely unnoticeable to end users.
Further reading:
- Scope chain of JScript functions - JScript blog
OTHER TIPS
This is the kind of micro-optimization that's really a complete waste of time, but for what it's worth a common idiom is to write Javascript like this:
(function(window, undefined) {
// your code, thousands of lines of sheer beauty
})(this);
That gives you a local reference to "window", and a reliable "undefined" variable to boot.
Why is it a waste of time? Because for any ordinary code, you're talking about at most a millisecond or two shaved off the execution time. Nobody's ever going to notice that. Make sure that the actual algorithms you're using to do whatever it is you're coding are appropriate, and let the Javascript interpreter/JIT developers shave off those milliseconds for you. If you get obsessed with things like this, you're liable to end up with code that runs slower in the future because you'll have done weird things that end up not being optimized by the interpreter.