summaryrefslogtreecommitdiff
path: root/deps/node/benchmark/es/foreach-bench.js
blob: 25ea97b44d5695d25148b8fdd19f5da20ea0570b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';

const common = require('../common.js');

const bench = common.createBenchmark(main, {
  method: ['for', 'for-of', 'for-in', 'forEach'],
  count: [5, 10, 20, 100],
  n: [5e6]
});

function useFor(n, items, count) {
  bench.start();
  for (var i = 0; i < n; i++) {
    for (var j = 0; j < count; j++) {
      /* eslint-disable no-unused-vars */
      const item = items[j];
      /* esline-enable no-unused-vars */
    }
  }
  bench.end(n);
}

function useForOf(n, items) {
  var item;
  bench.start();
  for (var i = 0; i < n; i++) {
    for (item of items) {}
  }
  bench.end(n);
}

function useForIn(n, items) {
  bench.start();
  for (var i = 0; i < n; i++) {
    for (var j in items) {
      /* eslint-disable no-unused-vars */
      const item = items[j];
      /* esline-enable no-unused-vars */
    }
  }
  bench.end(n);
}

function useForEach(n, items) {
  bench.start();
  for (var i = 0; i < n; i++) {
    items.forEach((item) => {});
  }
  bench.end(n);
}

function main({ n, count, method }) {
  const items = new Array(count);
  var fn;
  for (var i = 0; i < count; i++)
    items[i] = i;

  switch (method) {
    case '':
      // Empty string falls through to next line as default, mostly for tests.
    case 'for':
      fn = useFor;
      break;
    case 'for-of':
      fn = useForOf;
      break;
    case 'for-in':
      fn = useForIn;
      break;
    case 'forEach':
      fn = useForEach;
      break;
    default:
      throw new Error(`Unexpected method "${method}"`);
  }
  fn(n, items, count);
}