1'use strict'; 2 3const common = require('../common.js'); 4const assert = require('assert'); 5 6const bench = common.createBenchmark(main, { 7 method: ['swap', 'destructure'], 8 n: [1e8], 9}); 10 11function runSwapManual(n) { 12 let x, y, r; 13 bench.start(); 14 for (let i = 0; i < n; i++) { 15 x = 1; 16 y = 2; 17 r = x; 18 x = y; 19 y = r; 20 assert.strictEqual(x, 2); 21 assert.strictEqual(y, 1); 22 } 23 bench.end(n); 24} 25 26function runSwapDestructured(n) { 27 let x, y; 28 bench.start(); 29 for (let i = 0; i < n; i++) { 30 x = 1; 31 y = 2; 32 [x, y] = [y, x]; 33 assert.strictEqual(x, 2); 34 assert.strictEqual(y, 1); 35 } 36 bench.end(n); 37} 38 39function main({ n, method }) { 40 switch (method) { 41 case 'swap': 42 runSwapManual(n); 43 break; 44 case 'destructure': 45 runSwapDestructured(n); 46 break; 47 default: 48 throw new Error(`Unexpected method "${method}"`); 49 } 50} 51