Question

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

Was it helpful?

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:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top