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