Javascript:多次调用对象属性
我有一个对象:
var object = {
string1 : 'hello',
string2 : 'world'
}
如果我想调用 object
的 string2
属性,多次调用它是否会更慢,例如:
...object.string2...
...object.string2...
或者创建引用会更快对于它来说,保存参数值的原因是:
var string2 = object.string2;
...string2...
...string2...
我认为第二个可能更快的原因是,因为我现在认为第一个总是扫描整个对象以获取值。
I have an object:
var object = {
string1 : 'hello',
string2 : 'world'
}
And If I want to call the string2
property of the object
is it slower to call it multiple times like:
...object.string2...
...object.string2...
or it would be faster to create a reference for it what holds the value of the parameter like:
var string2 = object.string2;
...string2...
...string2...
The reason why I think that the second one could be faster, because I think right now that the first one always scans the whole object to grab the value.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的——第二个更快,因为 JavaScript 不需要每次都执行 string2 的查找。这种变化在以下方面更为深刻:
与
在该示例中,必须扫描 foo 来查找 bar。然后必须扫描 bar 来查找 baz。等等。
在您的示例中,除非您对 string2 进行大量工作,否则增益将很小,但您说它更快是正确的。
You are correct - the second one is faster, because JavaScript does not need to perform the lookup of string2 each time. The change is even more profound in something like this:
versus
In that example, foo must be scanned for bar. Then bar must be scanned for baz. Et cetera.
In your example the gain will be minimal unless you are doing a lot of work with string2, but you are correct in saying that it is faster.
在你的情况下这并不重要。但对于具有大原型块的大对象 - 你是对的。
但是你可能会在速度上获胜,但在功能上松散,因为 var a = obje.property 按值处理 - 而不是通过引用,如果 obj.property 将动态更改,则变量 a 将具有 obj.property 的旧值
In you case this does not matter . But for big object with big prototype chunks - you right.
But you may win in speed but loose in functionality because var a = obje.property coping by value - not by reference and if obj.property will be change dynamically that variable a will have old value of obj.property