• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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, y = 2;
16    r = x;
17    x = y;
18    y = r;
19    assert.strictEqual(x, 2);
20    assert.strictEqual(y, 1);
21  }
22  bench.end(n);
23}
24
25function runSwapDestructured(n) {
26  let x, y;
27  bench.start();
28  for (let i = 0; i < n; i++) {
29    x = 1, y = 2;
30    [x, y] = [y, x];
31    assert.strictEqual(x, 2);
32    assert.strictEqual(y, 1);
33  }
34  bench.end(n);
35}
36
37function main({ n, method }) {
38  switch (method) {
39    case 'swap':
40      runSwapManual(n);
41      break;
42    case 'destructure':
43      runSwapDestructured(n);
44      break;
45    default:
46      throw new Error(`Unexpected method "${method}"`);
47  }
48}
49