Skip to content

Commit

Permalink
benchmark: benchmark comparing forEach with for
Browse files Browse the repository at this point in the history
PR-URL: #11582
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
  • Loading branch information
jasnell authored and italoacasas committed Mar 20, 2017
1 parent d0fb578 commit dcac2d8
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions benchmark/es/foreach-bench.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
'use strict';

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

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

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

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

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

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

function main(conf) {
const n = +conf.millions * 1e6;
const count = +conf.count;

const items = new Array(count);
var i;
var fn;
for (i = 0; i < count; i++)
items[i] = i;

switch (conf.method) {
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');
}
fn(n, items, count);
}

0 comments on commit dcac2d8

Please sign in to comment.