1'use strict'; 2const common = require('../common.js'); 3const assert = require('assert'); 4 5const bench = common.createBenchmark(main, { 6 loopMethod: ['forEach', 'iterator'], 7 n: [1e6] 8}); 9 10const str = 'one=single&two=first&three=first&two=2nd&three=2nd&three=3rd'; 11 12function forEach(n) { 13 const params = new URLSearchParams(str); 14 const noDead = []; 15 const cb = (val, key) => { 16 noDead[0] = key; 17 noDead[1] = val; 18 }; 19 20 bench.start(); 21 for (let i = 0; i < n; i += 1) 22 params.forEach(cb); 23 bench.end(n); 24 25 assert.strictEqual(noDead[0], 'three'); 26 assert.strictEqual(noDead[1], '3rd'); 27} 28 29function iterator(n) { 30 const params = new URLSearchParams(str); 31 const noDead = []; 32 33 bench.start(); 34 for (let i = 0; i < n; i += 1) { 35 for (const pair of params) { 36 noDead[0] = pair[0]; 37 noDead[1] = pair[1]; 38 } 39 } 40 bench.end(n); 41 42 assert.strictEqual(noDead[0], 'three'); 43 assert.strictEqual(noDead[1], '3rd'); 44} 45 46function main({ loopMethod, n }) { 47 switch (loopMethod) { 48 case 'forEach': 49 forEach(n); 50 break; 51 case 'iterator': 52 iterator(n); 53 break; 54 default: 55 throw new Error(`Unknown method ${loopMethod}`); 56 } 57} 58