ariya.io About Talks Articles

JavaScript object structure: speed matters

2 min read

A common pattern to speed-up the performance of your JavaScript code is to leverage the optimized property access found in modern JavaScript engines. In fact, fast property access is a key in design elements of V8. It is also achieved in JavaScriptCore, the default engine behind WebKit, via polymorphic inline cache. Firefox enjoys the same speed-up also through the same polymorphic inline cache available in its JägerMonkey project.

How would you take advantage of this feature? It’s very simple. In practice, it’s a matter of being careful with object construction. For example, rather than doing the following:

var universe = {
  answer: 42
};
// do something else
universe.panic = false;

it’s recommended to implement it this way:

var universe = {
  answer: 42,
  panic: true
};
// do something else
universe.panic = false;

Basically, try to keep the object structure unchanged (obviously it may require some change in your logic). If you don’t know the value of a certain property, e.g. panic in the above example, that’s totally fine. You can always change the property value later, but you would help the JavaScript engine if you avoid adding and removing properties after the object is created.

For real-world examples, check out Esprima development. In revision 4f9af77ddc, carefully fixing the structure of token object improves Firefox 9 performance. The similar trick is used to regain the speed as a new feature was introduced.

Before you go wild and obfuscate your code to take advantage of this speedier property access, remember one thing: always optimize responsibly. First, make sure that the bottleneck is not somewhere else. In addition, avoid the temptation of a higher performant variant if that will significantly reduce the readability of the code.

OK properties, off you go!

Related posts:

♡ this article? Explore more articles and follow me Twitter.

Share this on Twitter Facebook