Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
Add Comment
Please, Sign In to add comment