Back to all posts

The cost of object literals

When building Javascript applications we often handle configurations with objects. If we build applications with frameworks such as React, it's not uncommon that these objects tend to be quite large. Often these applications are dependent on these configurations for their first rendering. This raises an interesting question about Javascript performance and why there is a difference in speed between reading object literals and parsing objects as strings.

Consider the following example from Google dev post

// Data as object literal
const data = { foo: 42, bar: 1337 }; // ๐ŸŒ
// Data as a string parse with JSON.parse
const data = JSON.parse('{"foo":42,"bar":1337}'); // ๐Ÿš€

For JSON-compatible objects, parsing the stringified object can be 1.2x to 2x faster than reading the object literal, depending on object size and browser.

So why is reading the object literal slower?

The interpreter for object literals needs to be equipped to interpret the entire Javascript language. This is because besides just reading the JSON content of an object literal, the interpreter is trying to determine if it's reading Javascript constructs or JSON data.

JSON.parse on the other hand might feel like an additional layer of handling data, but in reality it's about knowing what type of data we are working with and applying the most informed choice of parsing. The JSON.parse is a function that exclusively focuses on parsing JSON, which is much faster. Note that this doesn't mean that we always should interpret objects as strings. A good rule of thumb is to apply this technique for objects of 10 kB or larger.


This article is my 3rd oldest. It is 262 words long, and itโ€™s got 0 comments for now.