Javascript Object Reference Caching
Solution 1:
It will be an improvement, but we're talking a completely negligible one.
It takes time to lookup a property of an object, but it's really quite fast.
If you're doing this for performance reasons, don't.
If you're doing this to make your code more readable/maintainable, then that's OK.
EDIT:
I created a benchmark to test this: Run the benchmark
vardata = {a: {b: {c: {d: 1}}}};
var cache = data.a.b.c.d;
// uncached 901,326,988 ±1.03% fastest// cached 879,568,962 ±0.95% 2% slower// Chrome 41 on OSX 10.10
Well that's surprising !
Turns out it's faster to just call
data.a.b.c.d + 1
Instead of
cache + 1
I'm sure this varies based on implementation of JavaScript. Providing a specific reason for why this occurs will be left to other genii that dig around in js engine internals.
So with that in mind, my recommendations above stay the same:
If you're doing this for performance reasons, don't — it's actually slower.
If you're doing this to make your code more readable/maintainable, then that's OK — the performance cost is worth the value of more legible code.
Solution 2:
This is implementation-specific and depends heavily on the underlying JavaScript engine.
For example, v8 engine (Chrome & maybe others) uses so-called hidden classes for JavaScript objects. This has the benefit that each object's property is known to be at a fixed offset in the memory and thus accessing an object's property is very fast.
On the other hand, some implementations (I only work with node.js so I do not have any particular browser references that use this method, but Firefox seems to be using this method - see below) may use dictionaries to map objects' properties to their memory locations. Dictionary lookups require more operations (more CPU cycles) and so they are somewhat slower.
In general, however, we are talking about extremely small difference.
To summarise, performance-wise this has almost no impact on your code performance. However, code style-wise, it can improve readability and maintainability of your code.
This jsperf (courtesy of @naomik) seems to support this - when run in Chrome, the difference is about 5%, whereas for Firefox it is a whopping 29%.
Post a Comment for "Javascript Object Reference Caching"