Is Caching A Double-Dot JS Function Worth It?

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

thomas michael wallace
tomincode
2 min readJul 28, 2017

--

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 hasOwnProperty() 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 Object.prototype.hasOwnProperty.call(obj, key) 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:

const has = Object.prototype.hasOwnProperty; // cache the lookup once, in module scope.

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 hasProperty 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!

--

--