Skip to content

Commit dcac2d8

Browse files
jasnellitaloacasas
authored andcommitted
benchmark: benchmark comparing forEach with for
PR-URL: #11582 Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Colin Ihrig <[email protected]>
1 parent d0fb578 commit dcac2d8

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

benchmark/es/foreach-bench.js

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
5+
const bench = common.createBenchmark(main, {
6+
method: ['for', 'for-of', 'for-in', 'forEach'],
7+
count: [5, 10, 20, 100],
8+
millions: [5]
9+
});
10+
11+
function useFor(n, items, count) {
12+
var i, j;
13+
bench.start();
14+
for (i = 0; i < n; i++) {
15+
for (j = 0; j < count; j++) {
16+
/* eslint-disable no-unused-vars */
17+
var item = items[j];
18+
/* esline-enable no-unused-vars */
19+
}
20+
}
21+
bench.end(n / 1e6);
22+
}
23+
24+
function useForOf(n, items) {
25+
var i, item;
26+
bench.start();
27+
for (i = 0; i < n; i++) {
28+
for (item of items) {}
29+
}
30+
bench.end(n / 1e6);
31+
}
32+
33+
function useForIn(n, items) {
34+
var i, j, item;
35+
bench.start();
36+
for (i = 0; i < n; i++) {
37+
for (j in items) {
38+
/* eslint-disable no-unused-vars */
39+
item = items[j];
40+
/* esline-enable no-unused-vars */
41+
}
42+
}
43+
bench.end(n / 1e6);
44+
}
45+
46+
function useForEach(n, items) {
47+
var i;
48+
bench.start();
49+
for (i = 0; i < n; i++) {
50+
items.forEach((item) => {});
51+
}
52+
bench.end(n / 1e6);
53+
}
54+
55+
function main(conf) {
56+
const n = +conf.millions * 1e6;
57+
const count = +conf.count;
58+
59+
const items = new Array(count);
60+
var i;
61+
var fn;
62+
for (i = 0; i < count; i++)
63+
items[i] = i;
64+
65+
switch (conf.method) {
66+
case 'for':
67+
fn = useFor;
68+
break;
69+
case 'for-of':
70+
fn = useForOf;
71+
break;
72+
case 'for-in':
73+
fn = useForIn;
74+
break;
75+
case 'forEach':
76+
fn = useForEach;
77+
break;
78+
default:
79+
throw new Error('Unexpected method');
80+
}
81+
fn(n, items, count);
82+
}

0 commit comments

Comments
 (0)