<!--your preparation HTML code goes here-->
let url = URL.createObjectURL(new Blob([JSON.stringify({a:3,b:3,c:3,n:6,baeij:2,ifjq3:[1,2,3,4,5]})],{type:'application/json'}))
function finish() {
deferred.resolve()
}
function auto(j) {
j.json().then(finish)
}
function parse(j) {
j.text().then(JSON.parse).then(finish)
}
fetch(url).then(auto)
fetch(url).then(parse)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
fetch.json() | |
fetch+json.parse |
Test name | Executions per second |
---|---|
fetch.json() | 1448.3 Ops/sec |
fetch+json.parse | 1373.3 Ops/sec |
The benchmark you've provided compares two different approaches to fetching JSON data and processing it in JavaScript. The two methods being tested are:
Response.json()
method directly on the Fetch API response.Response.text()
followed by JSON.parse()
to handle the JSON data.fetch(url).then(auto)
: This test case utilizes the built-in .json()
method of the Fetch API. The auto
function is called when the response is successfully parsed into a JSON object. This is considered a more straightforward method for extracting JSON data from a response.
fetch(url).then(parse)
: In this test case, the response is first converted to text with the .text()
method. Then, the text is manually parsed using JSON.parse()
, capturing the invoking function in the parse
function.
Response.json()
Pros:
.json()
method automatically handles any issues that might arise with malformed JSON during parsing without requiring additional checks for proper formatting.Cons:
Response.text()
and JSON.parse()
Pros:
Cons:
.json()
method.The benchmark results indicated that the fetch.url().then(auto)
(using .json()
) had a higher execution rate of approximately 1448.30 executions per second, while the fetch(url).then(parse)
(using JSON.parse()
) achieved around 1373.35 executions per second. This suggests that using the .json()
method is generally more efficient in this specific test.
Response.json()
might not be available..json()
method is usually preferred due to its simplicity. The manual method could be more appropriate for APIs returning mixed content types.Axios: A popular library for making HTTP requests in JavaScript that simplifies the fetching and parsing of JSON data. It automatically converts responses to JSON, similar to the Fetch API's .json()
, but also offers additional features like interceptors.
jQuery AJAX: While not as common in modern web development, jQuery provides powerful AJAX utilities that can simplify fetching and manipulating remote data, though it adds an additional dependency.
Fetch with Async/Await: Instead of using .then()
, developers can also utilize async/await
syntax for more readable asynchronous code for both methods mentioned.
In summary, while both methods are functional, using Response.json()
generally offers a more efficient and cleaner approach when working specifically with JSON data.