Skip to content

Instantly share code, notes, and snippets.

@rotu
Created September 23, 2023 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rotu/799f0608bd3ede48b9f8f1280876fb05 to your computer and use it in GitHub Desktop.
Save rotu/799f0608bd3ede48b9f8f1280876fb05 to your computer and use it in GitHub Desktop.
iterator microbenchmark shootout
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