0

Does declaring a new variable containing child objects execute faster than using the full path?

Ie, does this:

var a = main.data.category[main.data.constants.activecategory].subcategory.subcategoryobject.subcategory.subcategoryobject.subcategoryobjectdata.constants;

a.first = someFunction();
a.second = someArray;
a.third = someObject;

execute faster than this:

main.data.category[main.data.constants.activecategory].subcategory.subcategoryobject.subcategory.subcategoryobject.subcategoryobjectdata.constants.first = someFunction();
main.data.category[main.data.constants.activecategory].subcategory.subcategoryobject.subcategory.subcategoryobject.subcategoryobjectdata.constants.second = someArray;
main.data.category[main.data.constants.activecategory].subcategory.subcategoryobject.subcategory.subcategoryobject.subcategoryobjectdata.constants.third = someObject;

It's obviously easier to read, but does it execute faster - even if it's not significantly so?

Daniel Bengtsson
  • 302
  • 1
  • 3
  • 12
  • 1
    Go for readability. The performance gain is going to be irrelevant unless you're doing it millions of times. But if you're curious, just use console.time and console.timeEnd and put it in a loop of a few million (in both Chrome and Firefox since they have different JS engines) – user2740650 Jul 06 '20 at 03:42
  • That's what I have been doing for years and years now - I'm just curious as I can see it going both ways in terms of performance.var a = ... is just a reference here. If the reference is to the memory slot in the engine then I can see "var a = ..." being faster. If however the reference is to the full path which then needs to be calculated each time regardless then I can see the full path being faster. Thanks for the console.timeEnd thing - I was hoping to solve this on a theoretical level, but I will resort to creating loads of junk data and testing it if no concensus is reached. – Daniel Bengtsson Jul 06 '20 at 04:08
  • 1
    On a "theoretical level", the variable reference would be faster. Practically speaking, if that second block of code was marked as "hot" by the optimizer, it would probably end up being as fast as the variable reference anyway. As was already suggested, go for readability. Let the engines deal with micro-optimizations. – Patrick Roberts Jul 06 '20 at 04:15
  • @PatrickRoberts Yeah, see that's what makes logical sense to me too, but then I realized that that was something I had just assumed rather than investigated. I did a test now, and the theory does indeed hold up. Only assigned a substr of 3 characters and did 1+1 to a fairly deep object and that was roughly 3,5% faster with assigned variable reference. Way more than I thought. So in conclusion - the test data suggest that assigning a variable reference is not only better for readability, it is also faster as of todays three biggest and most recent browser versions. – Daniel Bengtsson Jul 06 '20 at 05:10

0 Answers0