Skip to content

Instantly share code, notes, and snippets.

@rotu
Last active October 28, 2024 02:12
Show Gist options
  • Save rotu/3182a9387d413c1a3fe4c23bf808d54b to your computer and use it in GitHub Desktop.
Save rotu/3182a9387d413c1a3fe4c23bf808d54b to your computer and use it in GitHub Desktop.
Array of object iteration strategies, benchmarked
import { assert } from 'jsr:@std/assert'
const COUNT = 8
const ar = []
for (let i = 0; i < COUNT; ++i) {
ar.push({ x: Math.random() * 1000 })
}
const sum = ar.reduce((a, obj) => (a + obj.x), 0)
function mapX() {
return ar.map((obj) => obj.x)
}
Deno.bench('ar.map(o=>o.x)', () => {
let s = 0
for (const x of mapX()) {
s += x
}
assert(s === sum)
})
function arrayFrom() {
return Array.from(ar, (obj) => obj.x)
}
Deno.bench('Array.from(ar,o=>o.x)', () => {
let s = 0
for (let x of arrayFrom()) {
s += x
}
assert(s === sum)
})
function* generateXs(a) {
for (const o of a) {
yield o.x
}
}
Deno.bench('generator yield', () => {
let s = 0
for (const x of generateXs(ar)) {
s += x
}
assert(s === sum)
})
function visitX(fn) {
ar.forEach((o) => fn(o.x))
}
Deno.bench('visitor (ar.forEach(o=>fn(o.x))', () => {
let s = 0
visitX((x) => {
s += x
})
assert(s === sum)
})
function arFromLoopPush() {
const result = []
for (const a of ar) {
result.push(a.x)
}
return result
}
Deno.bench('copy array', () => {
let s = 0
for (const x of arFromLoopPush()) {
s += x
}
assert(s === sum)
})
function iterateX(a) {
return {
[Symbol.iterator]: () => {
const innerIt = a[Symbol.iterator]()
return {
next: () => {
const innerNext = innerIt.next()
return {
done: innerNext.done,
value: innerNext.value?.x,
}
},
}
},
}
}
Deno.bench('x iterator', () => {
let s = 0
for (const x of iterateX(ar)) {
s += x
}
assert(s === sum)
})
@rotu
Copy link
Author

rotu commented Oct 28, 2024

deno bench iterator.bench.js
    CPU | Apple M3
Runtime | Deno 2.0.3 (aarch64-apple-darwin)

file:///Users/dan/Source/MiniProjects/iterator.bench.js

benchmark                         time/iter (avg)        iter/s      (min … max)           p75      p99     p995
--------------------------------- ----------------------------- --------------------- --------------------------
ar.map(o=>o.x)                            46.6 ns    21,480,000 ( 40.7 ns …  76.0 ns)  48.9 ns  56.3 ns  60.8 ns
Array.from(ar,o=>o.x)                    286.9 ns     3,485,000 (272.2 ns … 313.5 ns) 290.9 ns 308.8 ns 313.5 ns
generator yield                          193.0 ns     5,181,000 (179.7 ns … 214.9 ns) 196.2 ns 208.8 ns 210.8 ns
visitor (ar.forEach(o=>fn(o.x))           32.8 ns    30,450,000 ( 25.1 ns …   1.7 µs)  32.1 ns  42.5 ns  57.6 ns
copy array                                34.7 ns    28,800,000 ( 28.8 ns … 342.4 ns)  35.7 ns  52.1 ns  61.0 ns
x iterator                               222.4 ns     4,496,000 (211.8 ns … 246.4 ns) 226.7 ns 239.7 ns 243.1 ns

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment