alt
alt

Reputation: 13907

JavaScript: is it faster to cache deeply nested variables?

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?

Upvotes: 8

Views: 1596

Answers (2)

AlphaG33k
AlphaG33k

Reputation: 1678

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

Upvotes: 1

jfriend00
jfriend00

Reputation: 707406

As with all performance questions of importance, it is always best to test your specific situation in a tool like jsperf.com 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.com/cache-deep-reference, the cached reference was more than 2x faster in chrome and more than 4x faster in IE10.

Upvotes: 9

Related Questions