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.
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.