Skip to content

Instantly share code, notes, and snippets.

@nns2009
Last active August 4, 2025 01:10
Show Gist options
  • Select an option

  • Save nns2009/e59d81140696008749dc5b8df9258cc8 to your computer and use it in GitHub Desktop.

Select an option

Save nns2009/e59d81140696008749dc5b8df9258cc8 to your computer and use it in GitHub Desktop.
I was wondering how much overhead Promise.resolve and Promise.race have. Turns out: relatively huge, but at the same time - insignificant in absolute delay for the use-case I was considering.
let sleep = s => new Promise(resolve => setTimeout(resolve, s * 1000));
let asyncResolve = v => new Promise(resolve => setTimeout(() => resolve(v), 0));
async function simplePromiseTime(promiseStart) {
let before = performance.now();
await promiseStart();
let after = performance.now();
return (after - before) / 1000;
}
let maxValue = 10**4;
function syncResolveLoop() {
let res = 0;
for (let i = 0; i < maxValue; i++)
res += i**2;
return res;
}
async function directResolveLoop() {
let res = 0;
for (let i = 0; i < maxValue; i++)
res += await Promise.resolve(i**2);
return res;
}
async function asyncResolveLoop() {
let res = 0;
for (let i = 0; i < maxValue; i++)
res += await asyncResolve(i**2);
return res;
}
async function raceResolveLoop() {
let res = 0;
for (let i = 0; i < maxValue; i++)
res += await Promise.race([ Promise.resolve(i**2) ]);
return res;
}
console.log(`sync resolve:`, await simplePromiseTime(syncResolveLoop));
console.log(`direct resolve:`, await simplePromiseTime(directResolveLoop));
console.log(`async resolve:`, await simplePromiseTime(asyncResolveLoop));
console.log(`race resolve:`, await simplePromiseTime(raceResolveLoop));
/*
Edge (Chromium-based):
sync resolve: 0.00030000019073486326
direct resolve: 0.021300000190734865
async resolve: 46.522800000190735
race resolve: 0.029900000095367432
Firefox:
sync resolve: 0
direct resolve: 0.007
async resolve: 156.639
race resolve: 0.036
-------------------------
Now let's set:
let maxValue = 10**4 * 100;
and comment out `async resolve` (because it is too slow)
Edge (Chromium-based):
sync resolve: 0.0019000000953674316
direct resolve: 6.396400000095367
race resolve: 7.11560000038147
Firefox:
sync resolve: 0.002
direct resolve: 0.811
race resolve: 3.517
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment