Search code examples
javascriptperformancewindowselfexplicit

Javascript use explicit self/window objects to improve performance


I read on MSDN that to improve scripting efficiency, you can use self to make implicit window references explicit.

  1. Do you know if this is true? Does this basically mean that for instance calling self.location is somewhay more efficient than calling simply location with no window opject before?

  2. Since the MSDN text is referred to the self and not window, does this performance increase happens only using self? According to here window and self and window.self are the same thing, so it shouldn't matter what we use, i'm asking only to make sure.

  3. Moreover following what stated in MSDN calling window.self should be somehow more performant than calling self because this last one is a property of window so by calling window.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:

    1. Look for location declared in the current scope, return and exit if found.
    2. Go up the scope hierarchy by one.
    3. 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: