Last active
October 28, 2024 02:12
-
-
Save rotu/3182a9387d413c1a3fe4c23bf808d54b to your computer and use it in GitHub Desktop.
Array of object iteration strategies, benchmarked
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
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) | |
}) |
Author
rotu
commented
Oct 28, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment