开发者

Javascript: Calling Object Properties Multiple Times

开发者 https://www.devze.com 2023-03-28 20:40 出处:网络
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:

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开发者_如何学Go 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.


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:

(do stuff with foo.bar.baz.qux)

versus

var property = foo.bar.baz.qux;
(do stuff with property)

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.


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

0

精彩评论

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