Created
June 15, 2018 20:18
-
-
Save dphilipson/26eb0f96627f268e47f4992c3c328fca to your computer and use it in GitHub Desktop.
Benchmarks demonstrating interesting properties of optimization around function arity in JavaScript
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 Benchmark from "benchmark"; | |
const array: number[] = []; | |
for (let i = 0; i < 100000; i++) { | |
array.push(i); | |
} | |
function map<T, U>(arr: T[], f: (item: T) => U): U[] { | |
const result: U[] = []; | |
for (let i = 0, { length } = arr; i < length; i++) { | |
result.push(f(arr[i])); | |
} | |
return result; | |
} | |
function mapIndexed<T, U>(arr: T[], f: (item: T, index: number) => U): U[] { | |
const result: U[] = []; | |
for (let i = 0, { length } = arr; i < length; i++) { | |
result.push(f(arr[i], i)); | |
} | |
return result; | |
} | |
function mapOptimized<T, U>(arr: T[], f: (item: T, index: number) => U): U[] { | |
const needsIndex = f.length > 1; | |
const result: U[] = []; | |
for (let i = 0, { length } = arr; i < length; i++) { | |
result.push(needsIndex ? f(arr[i], i) : (f as any)(arr[i])); | |
} | |
return result; | |
} | |
new Benchmark.Suite() | |
.add("map()", () => { | |
map(array, x => 2 * x); | |
}) | |
.add("mapIndexed() with one arg", () => { | |
mapIndexed(array, x => 2 * x); | |
}) | |
.add("mapIndexed() with two args", () => { | |
mapIndexed(array, (x, _) => 2 * x); | |
}) | |
.add("mapOptimized() with one arg", () => { | |
mapOptimized(array, x => 2 * x); | |
}) | |
.add("mapOptimized() with two args", () => { | |
mapIndexed(array, (x, _) => 2 * x); | |
}) | |
.on("cycle", function(event: any) { | |
console.log(String(event.target)); | |
}) | |
.run({ async: true }); | |
// map() x 523 ops/sec ±1.10% (86 runs sampled) | |
// mapIndexed() with one arg x 412 ops/sec ±1.75% (82 runs sampled) | |
// mapIndexed() with two args x 508 ops/sec ±2.82% (87 runs sampled) | |
// mapOptimized() with one arg x 512 ops/sec ±2.68% (87 runs sampled) | |
// mapOptimized() with two args x 514 ops/sec ±1.68% (86 runs sampled) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment