2017-02-25 22:06:31 -08:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const common = require('../common.js');
|
|
|
|
|
|
|
|
const bench = common.createBenchmark(main, {
|
|
|
|
method: ['for', 'for-of', 'for-in', 'forEach'],
|
|
|
|
count: [5, 10, 20, 100],
|
2023-01-29 20:13:35 +02:00
|
|
|
n: [5e6],
|
2017-02-25 22:06:31 -08:00
|
|
|
});
|
|
|
|
|
2018-03-17 20:49:09 +05:30
|
|
|
function useFor(n, items, count) {
|
2017-02-25 22:06:31 -08:00
|
|
|
bench.start();
|
2020-01-24 18:12:49 +01:00
|
|
|
for (let i = 0; i < n; i++) {
|
|
|
|
for (let j = 0; j < count; j++) {
|
2019-03-27 00:23:31 +08:00
|
|
|
// eslint-disable-next-line no-unused-vars
|
2017-09-13 22:48:53 -03:00
|
|
|
const item = items[j];
|
2017-02-25 22:06:31 -08:00
|
|
|
}
|
|
|
|
}
|
2018-03-17 20:49:09 +05:30
|
|
|
bench.end(n);
|
2017-02-25 22:06:31 -08:00
|
|
|
}
|
|
|
|
|
2018-03-17 20:49:09 +05:30
|
|
|
function useForOf(n, items) {
|
2017-02-25 22:06:31 -08:00
|
|
|
bench.start();
|
2020-01-24 18:12:49 +01:00
|
|
|
for (let i = 0; i < n; i++) {
|
2022-02-02 21:28:06 -08:00
|
|
|
// eslint-disable-next-line no-unused-vars, no-empty
|
2019-03-27 00:23:31 +08:00
|
|
|
for (const item of items) {}
|
2017-02-25 22:06:31 -08:00
|
|
|
}
|
2018-03-17 20:49:09 +05:30
|
|
|
bench.end(n);
|
2017-02-25 22:06:31 -08:00
|
|
|
}
|
|
|
|
|
2018-03-17 20:49:09 +05:30
|
|
|
function useForIn(n, items) {
|
2017-02-25 22:06:31 -08:00
|
|
|
bench.start();
|
2020-01-24 18:12:49 +01:00
|
|
|
for (let i = 0; i < n; i++) {
|
|
|
|
for (const j in items) {
|
2019-03-27 00:23:31 +08:00
|
|
|
// eslint-disable-next-line no-unused-vars
|
2018-01-23 13:18:30 +01:00
|
|
|
const item = items[j];
|
2017-02-25 22:06:31 -08:00
|
|
|
}
|
|
|
|
}
|
2018-03-17 20:49:09 +05:30
|
|
|
bench.end(n);
|
2017-02-25 22:06:31 -08:00
|
|
|
}
|
|
|
|
|
2018-03-17 20:49:09 +05:30
|
|
|
function useForEach(n, items) {
|
2017-02-25 22:06:31 -08:00
|
|
|
bench.start();
|
2020-01-24 18:12:49 +01:00
|
|
|
for (let i = 0; i < n; i++) {
|
2017-02-25 22:06:31 -08:00
|
|
|
items.forEach((item) => {});
|
|
|
|
}
|
2018-03-17 20:49:09 +05:30
|
|
|
bench.end(n);
|
2017-02-25 22:06:31 -08:00
|
|
|
}
|
|
|
|
|
2018-03-17 20:49:09 +05:30
|
|
|
function main({ n, count, method }) {
|
2017-02-25 22:06:31 -08:00
|
|
|
const items = new Array(count);
|
2020-01-24 18:12:49 +01:00
|
|
|
let fn;
|
|
|
|
for (let i = 0; i < count; i++)
|
2017-02-25 22:06:31 -08:00
|
|
|
items[i] = i;
|
|
|
|
|
2017-12-30 03:59:27 +01:00
|
|
|
switch (method) {
|
2017-02-25 22:06:31 -08:00
|
|
|
case 'for':
|
|
|
|
fn = useFor;
|
|
|
|
break;
|
|
|
|
case 'for-of':
|
|
|
|
fn = useForOf;
|
|
|
|
break;
|
|
|
|
case 'for-in':
|
|
|
|
fn = useForIn;
|
|
|
|
break;
|
|
|
|
case 'forEach':
|
|
|
|
fn = useForEach;
|
|
|
|
break;
|
|
|
|
default:
|
2018-01-23 13:18:30 +01:00
|
|
|
throw new Error(`Unexpected method "${method}"`);
|
2017-02-25 22:06:31 -08:00
|
|
|
}
|
2018-03-17 20:49:09 +05:30
|
|
|
fn(n, items, count);
|
2017-02-25 22:06:31 -08:00
|
|
|
}
|