Skip to content

Instantly share code, notes, and snippets.

@scarf005
Last active January 8, 2024 02:08
Show Gist options
  • Save scarf005/1e3dc3f158fc491bf69d32a6e30d47fb to your computer and use it in GitHub Desktop.
Save scarf005/1e3dc3f158fc491bf69d32a6e30d47fb to your computer and use it in GitHub Desktop.
Inline your callbacks
const f = (g: (x: number) => number) => (x: number) => g(x)
Deno.bench("closure directly", { baseline: true }, () => {
const foo = [...Array(1000).keys()].map(f((x) => x + 1))
})
Deno.bench("closure indirectly", () => {
const g = f((x) => x + 1)
const foo = [...Array(1000).keys()].map(g)
})
Deno.bench("closure very indirectly", () => {
const g = (x: number) => x + 1
const h = f(g)
const foo = [...Array(1000).keys()].map(h)
})
benchmark time (avg) iter/s (min … max) p75 p99 p995
----------------------------------------------------------------------------- -----------------------------
closure directly 17.2 µs/iter 58,139.5 (15.62 µs … 328.54 µs) 16.08 µs 64.62 µs 68.96 µs
closure indirectly 21.5 µs/iter 46,522.4 (19.92 µs … 130.17 µs) 20.75 µs 72.04 µs 77.75 µs
closure very indirectly 21.39 µs/iter 46,744.3 (19.88 µs … 518.67 µs) 20.62 µs 31.25 µs 96.71 µs
summary
closure directly
1.24x faster than closure very indirectly
1.25x faster than closure indirectly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment