开发者

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 the major browsers? Has anyone performed any good tests on this one开发者_开发知识库?


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

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 share the same namespace as variables (I think) and act like variables with regards to resolution.

There is no additional cost to using foo['bar'] instead of foo.bar, except perhaps optimizations by the Javscript engine (though if you're optimizing the latter it should be easy to optimize the former if the contents are literal).


Locally scoped variables will always be present on the local Variable Object, and so will be 'free'.

To reach a global variable while in a scope you will have to traverse the scope chain until reaching the global object, where it will be found on the [[global]] Variable Object. The cost here depends on the number of scopes in the chain.

When it comes to accessing variables in different windows, now that is a different story.
Most newer browsers isolate each window with its own threads and with its own stack, in order to improve stability, improve garbage collection, and to avoid having one windows thread crash the entire browser.
What this means for variable access is that variables in one window isn't directly accessible to another (on a different stack). So how is this solved?

To take Opera as an example, once one window tries to access another windows variables, Opera will actually pause execution, merge the two stacks and execution environments together, and then continue the execution.
I guess you might say that this is quite expensive :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜