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) => JSON.parse(response._body)).then(showResult)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
response.json | |
JSON.parse |
Test name | Executions per second |
---|---|
response.json | 161.6 Ops/sec |
JSON.parse | 165.8 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Purpose
The benchmark tests two different approaches to parse JSON data from an HTTP response:
response.json()
: This approach uses the fetch
API to make a request to a URL, which returns a promise that resolves with the parsed JSON data.JSON.parse(response._body)
: This approach parses the raw JSON data directly from the _body
property of the HTTP response object.Options Compared
The two options being compared are:
response.json()
method to parse JSON data from an HTTP responseJSON.parse()
Pros and Cons of Each Approach
response.json()
:fetch
API polyfills) for older browsers.JSON.parse(response._body)
:fetch
API, making it suitable for older browsers.response.json()
.Library Used
In this benchmark, no external library is used. However, the fetch
API is a built-in feature in modern browsers, which provides a standardized way to make HTTP requests.
Special JS Feature or Syntax
None of the provided code uses special JavaScript features or syntax beyond what's necessary for parsing JSON data.
Other Alternatives
If you want to test other approaches to parse JSON data from an HTTP response, here are some alternatives:
XMLHttpRequest
instead of the fetch
API$.ajax()
methodKeep in mind that these alternatives may have different pros and cons compared to using the response.json()
or JSON.parse(response._body)
approaches.