Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance difference between location.href and window.location.href

Tags:

javascript

I have been read location.href is faster than window.location.href. But internally location.href is being read as window.location.href right? So how it would increase the significant performance?

like image 470
Al. Avatar asked Jul 20 '26 16:07

Al.


1 Answers

I have been read location.href is faster than window.location.href.

It might be infinitessimally faster, but nothing you'd notice in real life. Here's why:

Here's what the engine does (in theory) when it sees location.href:

  • Looks up location in the current scope; if not found, goes to the containing scope and so on, eventually reaching global scope.
  • At global scope, location is found as a property of the global object.
  • Then it looks up the href property on the location object.

Here's what the engine does (in theory) when it sees window.location.href:

  • Looks up window in the current scope; if not found, goes to the containing scope and so on, eventually reaching global scope.
  • At global scope, window is found as a property of the global object; it's a property the global object uses to refer to itself.
  • Then it looks up the location property on that object.
  • Then it looks up the href property on the location object.

So window.location.href requires one more property lookup than location.href does — barring any optimizations the JavaScript engine might be able to apply. But JavaScript performance is incredibly variable from engine to engine; your mileage may vary. Here's a benchmark that FB55 put together showing that the theory above is borne out by experimental results; location.href is indeed faster. In that particular test.

Gratuitous benchmark screenshot

(Blue = location.href, red = window.location.href; longer lines = faster performance.)

More to the point: Does it really matter? Not in the real world, no. You'd have to be doing this millions of times for there to be any human-perceptible difference. But that's the explanation for why you'll see people saying this about globals like location (or any other global, built-in or added by your own code).

like image 84
T.J. Crowder Avatar answered Jul 22 '26 07:07

T.J. Crowder