I run the following fetch/http request directly from my script in the browser:
const t0 = performance.now();
fetch("https://api.example/something", {
method: 'get',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(res=>res.json())
.then(res => {
const t1 = performance.now();
console.log(t1 - t0);
});
The timer returns on average 240ms.
After that I tried doing it using node:
var https = require('https');
https.globalAgent.maxSockets = 30;
https.globalAgent.keepAlive = true;
const performance = require('perf_hooks').performance;
const options = {
hostname: "api.example",
path: "/something",
method: 'GET',
forever: true,
pool: false,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
"Connection":"Keep-Alive"
}
}
const t0 = performance.now();
const req = https.request(options, res => {
res.on('data', d => {
const t1 = performance.now();
process.stdout.write(t1 - t0);
})
})
This returns on average 325 ms, which is considerable slower.
It is crucial that the api request is as fast as possible, this is the most important thing. The api is third party and therefor out of my control.
- Why the performance difference?
- What can I do to make it faster?
- Is the request within nodejs or the fetch within browser expected to be the fastest?