Skip to content

Instantly share code, notes, and snippets.

@conartist6
Last active June 12, 2022 11:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conartist6/5f1d0d1d15429fd9ccdfa7e161342010 to your computer and use it in GitHub Desktop.
Save conartist6/5f1d0d1d15429fd9ccdfa7e161342010 to your computer and use it in GitHub Desktop.
sync vs async for loops
function* range(end) {
for (let i = 0; i < end; i++) {
yield i;
}
}
const a = Array.from(range(65536));
module.exports['for await..of values from one chunk'] = {
fn: async function(deferred) {
let i = 0;
for await (const _ of a) {
i++;
}
deferred.resolve(i);
},
defer: true,
};
module.exports['for..of values from one chunk'] = {
fn: function() {
let i = 0;
for (const _ of a) {
i++;
}
return i;
},
};
// executed using this code: https://github.com/iter-tools/iter-tools/blob/0a567a2ebc76b9bd32354397709f8c1c6df8e615/benchmarks/index.js
/*
$ node --version
v15.2.1
$ node ./benchmarks/
Running 1 benchmarks, please wait...
async vs sync for loops
✓ for await..of values from one chunk x 80.75 ops/sec ±1.08% (74 runs sampled)
✓ for..of values from one chunk x 18,382 ops/sec ±0.47% (86 runs sampled)
Result: for..of values from one chunk is 22665.12% faster than for await..of values from one chunk.
Finished in 13 seconds
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment