Comparison of efficiency in declaring JSON data using JSON.parse versus an object literal

In a recent video from the 2019 Chrome Dev Summit titled "Boosting App Speed with JSON.parse", it was revealed that utilizing JSON.parse with a string literal instead of an object literal can result in a significant enhancement in speed. The official Google JSON.parse benchmarks clearly display a notable difference between the two approaches.

//Representing data using JS object literal
const info = { name: "John", age: 30 }; // 🐌

//Using JSON.parse for faster performance
const info = JSON.parse('{"name":"John","age":30}'); // 🚀

When working with JSON in JavaScript, are there any drawbacks to relying on JSON.parse over an object literal? Is it advisable to always define JSON data using JSON.parse method?

Answer №1

Using JSON.parse to parse a JSON string is beneficial as it returns an object, similar to what you get from an object literal.

When deciding between using an object literal versus JSON.parse, consider the following:

If the JSON string is only evaluated once, using JSON.parse is much quicker than using a JavaScript object literal, especially during cold loads. It's generally recommended to use this approach for objects larger than 10 kB — however, always test the actual performance impact before implementing any changes.

Source:

Answer №2

A MUST-READ!

While it is commonly believed that JSON.parse is faster, this may not always be the case when dealing with small objects.

/* JSON.parse */
start = new Date();

for(i=0; i<1000000; i++){ //creating from JSON
const miniObjectFromJson = JSON.parse('{"foo":42,"bar":1337}');
}
end = new Date()
timeGap = end - start; //457

/* JS object literal */
start = new Date()

for(i=0; i<1000000; i++){ //creating from JS Object Literal
const miniObjectFromLiteral = { foo: 42, bar: 1337 };
}
end = new Date()
timeGap = end - start; //9

The difference in performance can be significant, sometimes as much as tens of times.

Your conclusions may only be influenced by cases where the object size is massive, at least 8Mb.

Reference: https://www.youtube.com/watch?v=ff4fgQxPaO0

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for utilizing JsonConvert.DeserializeObject for nameless values:1. Create a class to

I came across a JSON string that looks like this: {"status":false,"data":{"errors":{"":"error45"}}} It's challenging to create a class for this JSON string because the last part doesn't have a na ...

Why does my page keep refreshing even after I close the model?

I am facing the following issues: 1- Whenever I try to close my model by clicking 'cancel', it causes the page to reload. 2- Clicking 'OK' does not send the 'DELETE' request to the server, nothing is received, and the page r ...

I am looking to insert an array of a specific type into a Postgres database using Node.js, but I am unsure of the process

query.callfunction('fn_create_mp_product', parameters, (err, result) => { if (err) { console.log(err) callback(err); } else { if (result.status == 'success') { callb ...

The JSONObject encountered an exception as it could not find a value for the

Encountering the same old exception while developing my android application The 'message' key is missing in the JSON data I'm certain that the JSONObject I possess holds the desired information: View and analyze my JSON Object for bette ...

Clone the children of an li element using jQuery, modify the text within a child tag, and then add it to

I have some awesome CSS that I want to recycle within a <ul>. My plan is to duplicate an existing <li> (to leverage the CSS), modify a <p> element, and then add it at the end of the <ul>. I believe I can achieve this by locating... ...

Invoking two asynchronous functions in React, where the first function relies on the state modified by the second function

Currently, I am working on an app that utilizes the Geoapify API. Within this app, I have implemented three primary API functions. Users are presented with two options on the user interface: they can manually search for cities or utilize their current loca ...

Can you create a stroke that is consistently the same width as the container BoxElement?

Utilizing a BoxElement provided by the blessed library, I am showcasing chat history. New sentences are inserted using pushLine. To enhance readability, days are separated by lines (which are added using pushLine). The width of each line matches that of t ...

Altering the appearance of an input field upon submission

https://jsfiddle.net/3vz45os8/7/ I'm working on a JSFiddle where I am trying to change the background color of input text based on whether the word is typed correctly or incorrectly. Currently, it's not functioning as expected and there are no e ...

Struggling to create a <td> with AngularJS directive

I am currently working on creating a directive for a large set of repeated HTML code that involves using tables and table data cells. Although I have experience creating directives for div elements in the past, this is my first attempt at incorporating the ...

JavaScript and jQuery are lightning fast, especially when the page is reloaded

I am currently working on a responsive website that uses liquid layouts. I have encountered challenges when incorporating images in the design, especially when dealing with different browsers like IE, Firefox, and Chrome. Recently, I faced another issue w ...

Trouble with firing the click event using document.createElement('a') in Firefox

I wrote a function that fetches arraybuffer data from my API, generates a temporary anchor element on the webpage, and then triggers a click event to download the file. Interestingly, this function performs as expected in Chrome. @action async loadVouc ...

Is there a way to assign the scroll event context to `document.body` instead of `window`?

Discovery As I delved into the intricacies of web development, I stumbled upon a curious observation. In a particular MDN page, I noticed that the left and right sidebars had their scrollbars contained within themselves. However, the content block's ...

The Twitch API is providing inaccurate channel information

Currently facing an issue while working with the Twitch API. When making a GET request to /api.twitch.tv/helix/search/channels?query=[STREAMER_NAME], it seems to be returning the wrong streamer/user. For instance: /api.twitch.tv/helix/search/channels?quer ...

What is the process for making a local storage item accessible to others on a network?

Can a local storage item be accessed from any computer on the network using the same Google Chrome extension that was previously set up? ...

Changing synchronous functions to asynchronous

Attempting to transform synchronous calls into asynchronous ones using when...done. Despite being new at this, after extensive reading on the topic for the past two days, my code should work as intended. However, while it does function, it doesn't exe ...

Tips for structuring commands in Discord.js

I'm in the process of restructuring my bot's commands. I currently have a folder called commands with all my commands inside, but I want to make it more organized by categorizing them into moderators, fun, and global like this: commands > mo ...

Reaching out to the Edge: Enhancing the jQuery Slider Experience

Alright, I'm really excited about using this amazing slider. What I love most is the "free mode" feature that creates this stunning sliding effect. The size and number of slides are absolutely perfect for me. But there's just one small adjustment ...

What techniques can be used to optimize the SEO of HTML generated by JavaScript? How does React.js go about achieving this

Is my webpage optimized for SEO if it was created using appendChild and innerHTML with JavaScript? Can react.js improve the SEO of a webpage? ...

Performing a targeted ajax request to retrieve a set of data

Is it possible to create a collection using a specific ajax call instead of fetching by its URL? Normally, when fetching by a collection, the URL in the collection is used. However, I need to retrieve results from an ajax call rather than the URL. $.ajax( ...

I'm baffled by the constant undefined status of the factory in AngularJS

I have encountered an issue where I defined a factory that makes a get request, but when I inject it into a controller, it always throws an undefined error. Below is the code for the factory: (function() { 'use strict'; var app = angul ...