const showResult = result => console.log(result);
const url = "https://www.googleapis.com/discovery/v1/apis";
fetch(url)
.then((response) => response.json())
.then(showResult)
const showResult = result => console.log(result);
const url = "https://www.googleapis.com/discovery/v1/apis";
fetch(url)
.then((response) => response.text())
.then((text) => JSON.parse(text))
.then(showResult)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
response.json() | |
JSON.parse() |
Test name | Executions per second |
---|---|
response.json() | 10919.1 Ops/sec |
JSON.parse() | 10569.7 Ops/sec |
The benchmark in question compares two different methods of handling JSON data received from a network response in JavaScript: using response.json()
versus using JSON.parse(response.text())
.
response.json()
JSON.parse(response.text())
response.text()
and is then parsed using JSON.parse()
.This benchmark does not involve the use of external libraries but utilizes native JavaScript features, specifically the Fetch API and the built-in JSON methods.
In addition to the provided methods, other alternatives could be considered for handling JSON responses:
$.getJSON()
which inherently parse JSON responses while managing the network request.In conclusion, the benchmark highlights a comparison between two approaches to JSON parsing in JavaScript, informing developers about their respective efficiencies and use cases. The findings suggest that using response.json()
is more efficient and concise for handling JSON responses compared to explicitly fetching the response as text and parsing it afterward.