How expensive are variables in JavaScript?

How expensive are local variables ( var v ), global variables ( window.v ) and cross-global variables ( parent.v ) in JavaScript, in major browsers? Has anyone done any good tests on this?

+4
source share
2 answers

Ignoring the pros and cons of the interpreter / parser, all that matters is how much the runtime should look at parts of the chain of regions.

Consider this simple example:

 foo = 42; // implicitly window.foo; cost: 2 var bar = 3; // cost: 1 function woot(a) { a; // cost: 1 bar; // cost: 2 foo; // cost: 3 var other = 9;// cost: 1 other; // cost: 1 a.something; // cost: 2 foo.win.fail.arg.func(a.something).thing = 0; // cost: 8 + 2 } woot(bar); // cost: 2 + 1 

Remember that functions use the same namespace as variables (I think) and act as variables with respect to resolution.

There is no additional cost to using foo['bar'] instead of foo.bar , with the possible exception of using the Javscript engine (although if you are optimizing the latter, it should be easy to optimize the former if the content is literal).

+8
source

Locally modified variables will always be present in the local variable object and therefore will be "free".

In order to cover a global variable while in scope, you will need to go through the chain of visibility before reaching the global object, where it will be found in the [[global]] variable object. The cost here depends on the number of areas in the chain.

When it comes to accessing variables in different windows, now this is a completely different story.
Most modern browsers isolate each window with its own streams and with its own stack, in order to increase stability, improve garbage collection, and to avoid the need for a single stream window to crash the entire browser.
What variable access means is that variables in one window are not directly accessible to another (in another stack). So how to solve this?

To take Opera as an example, as soon as one window tries to access other Windows variables, Opera will actually pause execution, merge the two stacks and runtimes together, and then continue execution.
I think you could say it is quite expensive :)

+2
source

Source: https://habr.com/ru/post/1310711/


All Articles