const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.googleapis.com/discovery/v1/apis');
xhr.onload = () => console.log(xhr.responseText);
xhr.send();
fetch('https://www.googleapis.com/discovery/v1/apis').then(response => response.text()).then(console.log)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
xhr | |
fetch |
Test name | Executions per second |
---|---|
xhr | 1627.0 Ops/sec |
fetch | 1417.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
What is being tested?
The provided benchmark tests two approaches to making HTTP requests: XMLHttpRequest
(XHR) and fetch
. The goal is to compare the performance of these two methods in terms of execution speed, without parsing the JSON response.
Options compared
The two options being compared are:
XMLHttpRequest
, setting the request method and URL, and handling the response.Pros and cons
Here are some pros and cons of each approach:
XHR (XMLHttpRequest)
Pros:
fetch
Cons:
Fetch
Pros:
fetch
Cons:
Library usage
In this benchmark, neither XHR nor fetch
uses a separate library. They are built-in JavaScript APIs.
Special JS feature or syntax
None of the two approaches use special JavaScript features or syntax that would require additional explanation.
Other considerations
When choosing between XHR and fetch
, consider the following factors:
fetch
is likely sufficient.fetch
is generally considered easier to read and write.Alternatives
If you're interested in exploring other approaches, here are some alternatives:
fetch
.In summary, this benchmark provides a fair comparison between XHR and fetch
, highlighting their strengths and weaknesses in terms of execution speed and ease of use. By understanding the pros and cons of each approach, developers can choose the best fit for their specific needs.