Is Caching A Double-Dot JS Function Worth It?

A quick and dirty piece of performance testing on the cached = Object.nested.function approach.

My linter told me off today. I’m normally in a position to coerce my object properties, so I rarely have to verify that a JavaScript object does really have the key I want. Today, however, I pulled out the old function- only to be told by the airbnb rules (who’s got the time to come up with their own?!) that I’d committed an awful crime.

The actual warning was about not trusting object properties, and instead I should be using the approach to avoid being tricked by shadowing. Something which you might argue is a bit onerous- but hey-hum; in a duck-typed world you can’t even trust a quack…

More interesting, however, was their example, in which they use the following snippet:

It made me remember my Python Performance 101- that property lookups are expensive so caching a ‘double-dot’ accessor is a good thing. However, I’d somehow neglected to transfer this lesson to JavaScript. As it is, the ES6 named function module pattern and a healthy tendency towards short files means that I very rarely find myself using nested functions- but still…

Premature optimisation is the work of the devil, and anything that obscures the meaning of code doubly so. (Although, I’d argue, wrapping the above in a function would probably improve readability). Even so, I decided to throw together a quick and dirty performance test to see if it was worth the effort:

You can run it yourself, but in this contrived solution, at least, there’s not much in it. And certainly not enough to refactor all your double-dots in JavaScript.

I’ll look forward to being proved wrong!

tomincode

writing daily lessons on the stuff tom does in code.

thomas michael wallace

Written by

writes about the stuff he does in code.

tomincode

tomincode

writing daily lessons on the stuff tom does in code.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade