JavaScript 中的变量有多昂贵? [英] How expensive are variables in JavaScript?
问题描述
局部变量 (var v
)、全局变量 (window.v
) 和跨全局变量 (parent.v
) 的开销有多大) 在 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.
考虑这个简单的例子:
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.
使用 foo['bar']
而不是 foo.bar
没有额外的成本,除了可能由 Javscript 引擎优化(尽管如果你正在优化后者应该很容易优化,如果内容是文字的话).
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).
这篇关于JavaScript 中的变量有多昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!