Guest User

Untitled

a guest
Jun 17th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. import Benchmark from "benchmark";
  2.  
  3. const array: number[] = [];
  4. for (let i = 0; i < 100000; i++) {
  5. array.push(i);
  6. }
  7.  
  8. function map<T, U>(arr: T[], f: (item: T) => U): U[] {
  9. const result: U[] = [];
  10. for (let i = 0, { length } = arr; i < length; i++) {
  11. result.push(f(arr[i]));
  12. }
  13. return result;
  14. }
  15.  
  16. function mapIndexed<T, U>(arr: T[], f: (item: T, index: number) => U): U[] {
  17. const result: U[] = [];
  18. for (let i = 0, { length } = arr; i < length; i++) {
  19. result.push(f(arr[i], i));
  20. }
  21. return result;
  22. }
  23.  
  24. function mapOptimized<T, U>(arr: T[], f: (item: T, index: number) => U): U[] {
  25. const needsIndex = f.length > 1;
  26. const result: U[] = [];
  27. for (let i = 0, { length } = arr; i < length; i++) {
  28. result.push(needsIndex ? f(arr[i], i) : (f as any)(arr[i]));
  29. }
  30. return result;
  31. }
  32.  
  33. new Benchmark.Suite()
  34. .add("map()", () => {
  35. map(array, x => 2 * x);
  36. })
  37. .add("mapIndexed() with one arg", () => {
  38. mapIndexed(array, x => 2 * x);
  39. })
  40. .add("mapIndexed() with two args", () => {
  41. mapIndexed(array, (x, _) => 2 * x);
  42. })
  43. .add("mapOptimized() with one arg", () => {
  44. mapOptimized(array, x => 2 * x);
  45. })
  46. .add("mapOptimized() with two args", () => {
  47. mapIndexed(array, (x, _) => 2 * x);
  48. })
  49. .on("cycle", function(event: any) {
  50. console.log(String(event.target));
  51. })
  52. .run({ async: true });
  53.  
  54. // map() x 523 ops/sec ±1.10% (86 runs sampled)
  55. // mapIndexed() with one arg x 412 ops/sec ±1.75% (82 runs sampled)
  56. // mapIndexed() with two args x 508 ops/sec ±2.82% (87 runs sampled)
  57. // mapOptimized() with one arg x 512 ops/sec ±2.68% (87 runs sampled)
  58. // mapOptimized() with two args x 514 ops/sec ±1.68% (86 runs sampled)
Add Comment
Please, Sign In to add comment