Let's say I have a variable nested deeply within a massive object which I re-use quite often:
i = 10000000;
while (i) {
i--;
document.write( bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p );
}
Would it be faster to cache it in a new variable outside of the loop?
v = bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p
and use that cached variable in my loop?
document.write ( v );
For the less visually oriented: Are JavaScript variables cached automatically or does the browser have to search through the larger variable each time it's requested?
Let's say I have a variable nested deeply within a massive object which I re-use quite often:
i = 10000000;
while (i) {
i--;
document.write( bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p );
}
Would it be faster to cache it in a new variable outside of the loop?
v = bigobject.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p
and use that cached variable in my loop?
document.write ( v );
For the less visually oriented: Are JavaScript variables cached automatically or does the browser have to search through the larger variable each time it's requested?
Share Improve this question asked Jun 29, 2013 at 4:50 altalt 14k21 gold badges82 silver badges123 bronze badges 1- most are cached, but if there's a getter in the path, like is mon with the DOM and expandos, everything to the right has to be re-gathered. – dandavis Commented Jun 29, 2013 at 4:56
2 Answers
Reset to default 9As with all performance questions of importance, it is always best to test your specific situation in a tool like jsperf. so you can measure the exact situation you care about and you should also run the test in multiple browsers to make sure what you're measuring is a general characteristic of the language implementation, not just a peculiarity to one browser.
In answer to your question, it is generally faster to cache a deep object reference if you are going to be accessing it multiple times.
In the specific example, I coded here: http://jsperf./cache-deep-reference, the cached reference was more than 2x faster in chrome and more than 4x faster in IE10.
I know that this is already answered however, I just made my own test for this and thought that someone on SO may find it useful:
ClassCreate('app').props.set('cipher', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'x', 'y', 'z']);
perfTest({
ns: 'noCache',
fn: function() {
for (var i = 0; i < 500; i++) {
console.log(app.props.get('cipher'));
}
}
});
perfTest({
ns: 'cached',
fn: function() {
var cipher = app.props.get('cipher');
for (var i = 0; i < 500; i++) {
console.log(cipher);
}
}
});
RESULTS
Cached variable x500: 812.261ms
Direct access to object in same x500 loop: 1050.416ms