Created
September 23, 2023 04:54
-
-
Save rotu/799f0608bd3ede48b9f8f1280876fb05 to your computer and use it in GitHub Desktop.
iterator microbenchmark shootout
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 { baseline, bench, run } = await import('https://esm.sh/mitata') | |
const data = Array.from(Array(1000).map(() => Math.random())) | |
bench('for {0;<;++} data[i]', () => { | |
let sum = 0 | |
for (let i = 0; i < data.length; ++i) { | |
sum += data[i] | |
} | |
return sum | |
}) | |
bench('for-of', () => { | |
let sum = 0 | |
for (const x of data) { | |
sum += x | |
} | |
return sum | |
}) | |
bench('for-of keys()', () => { | |
let sum = 0 | |
for (const i of data.keys()) { | |
sum += data[i] | |
} | |
return sum | |
}) | |
bench('for-of values()', () => { | |
let sum = 0 | |
for (const x of data.values()) { | |
sum += x | |
} | |
return sum | |
}) | |
bench('forEach', () => { | |
let sum = 0 | |
data.forEach((x) => { | |
sum += x | |
}) | |
return sum | |
}) | |
bench('reduce', () => { | |
const sum = data.reduce((x, y) => x + y, 0) | |
return sum | |
}) | |
bench('iterator object', () => { | |
let sum = 0 | |
const length = data.length | |
const e = { | |
[Symbol.iterator]: () => { | |
let i = 0 | |
return { | |
next: () => ({ | |
done: i >= length, | |
value: data[i++], | |
}), | |
} | |
}, | |
} | |
for (const x of e) { | |
sum += x | |
} | |
return sum | |
}) | |
bench('generator wrapping for {0;<;++}}', () => { | |
let sum = 0 | |
const custom_iter = { | |
[Symbol.iterator]: function* () { | |
let i = 0 | |
for (i = 0; i < data.length; ++i) { | |
yield data[i] | |
} | |
}, | |
} | |
for (const x of custom_iter) { | |
sum += x | |
} | |
return sum | |
}) | |
bench('wrapped generator (for-of yield)', () => { | |
let sum = 0 | |
const custom_iter = (function* () { | |
let x | |
for (x of data.values()) { | |
yield x | |
} | |
})() | |
for (const x of custom_iter) { | |
sum += x | |
} | |
return sum | |
}) | |
bench('delegated generator (yield* data.values())', () => { | |
const custom_iter2 = (function* () { | |
yield* data.values() | |
})() | |
let sum = 0 | |
for (const x of custom_iter2) { | |
sum += x | |
} | |
return sum | |
}) | |
await run({ | |
avg: true, // enable/disable avg column (default: true) | |
json: false, // enable/disable json output (default: false) | |
colors: false, // enable/disable colors (default: true) | |
min_max: false, // enable/disable min/max column (default: true) | |
collect: true, // enable/disable collecting returned values into an array during the benchmark (default: false) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment