Last active
October 31, 2023 09:56
-
-
Save Mutefish0/7f3d0fcf2d4b0fedc7a26079e0419234 to your computer and use it in GitHub Desktop.
Async Generator Performance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const C = 20_000_000; | |
async function* AG() { | |
const ret = []; | |
for (let i = 0; i < C; i++) { | |
ret.push(i); | |
} | |
for (const item of ret) { | |
yield item; | |
} | |
} | |
function* SG() { | |
const ret = []; | |
for (let i = 0; i < C; i++) { | |
ret.push(i); | |
} | |
for (const item of ret) { | |
yield item; | |
} | |
} | |
function LG() { | |
const ret = []; | |
for (let i = 0; i < C; i++) { | |
ret.push(i); | |
} | |
return ret; | |
} | |
let t0 = Date.now(); | |
let s = 0; | |
for await (const i of AG()) { | |
s += (i - 100) / 17; | |
s = s * s; | |
} | |
console.log("AsyncGenerator Await", Date.now() - t0); | |
t0 = Date.now(); | |
s = 0; | |
for (const i of LG()) { | |
s += (i - 100) / 17; | |
s = s * s; | |
} | |
console.log("Loop Loop", Date.now() - t0); | |
t0 = Date.now(); | |
s = 0; | |
for await (const i of LG()) { | |
s += (i - 100) / 17; | |
s = s * s; | |
} | |
console.log("Loop Await", Date.now() - t0); | |
t0 = Date.now(); | |
s = 0; | |
for await (const i of SG()) { | |
s += (i - 100) / 17; | |
s = s * s; | |
} | |
console.log("SyncGenetator Await", Date.now() - t0); | |
t0 = Date.now(); | |
s = 0; | |
for (const i of SG()) { | |
s += (i - 100) / 17; | |
s = s * s; | |
} | |
console.log("SyncGenerator Loop", Date.now() - t0); | |
// AsyncGenerator Await 2613 | |
// Loop Loop 368 | |
// Loop Await 2109 | |
// SyncGenetator Await 2475 | |
// SyncGenerator Loop 731 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment