Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 678
Marco Demaio Avatar asked Feb 16 '26 04:02

Marco Demaio


1 Answers

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.

like image 147
Pointy Avatar answered Feb 18 '26 16:02

Pointy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!