2016-04-15 09:25:58 -07:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
const common = require('../common.js');
|
|
|
|
const assert = require('assert');
|
|
|
|
|
|
|
|
const bench = common.createBenchmark(main, {
|
|
|
|
method: ['swap', 'destructure'],
|
2023-01-29 20:13:35 +02:00
|
|
|
n: [1e8],
|
2016-04-15 09:25:58 -07:00
|
|
|
});
|
|
|
|
|
2018-03-17 20:49:09 +05:30
|
|
|
function runSwapManual(n) {
|
2020-01-24 18:12:49 +01:00
|
|
|
let x, y, r;
|
2016-04-15 09:25:58 -07:00
|
|
|
bench.start();
|
2020-01-24 18:12:49 +01:00
|
|
|
for (let i = 0; i < n; i++) {
|
2020-11-24 14:11:20 +01:00
|
|
|
x = 1;
|
|
|
|
y = 2;
|
2016-04-15 09:25:58 -07:00
|
|
|
r = x;
|
|
|
|
x = y;
|
|
|
|
y = r;
|
|
|
|
assert.strictEqual(x, 2);
|
|
|
|
assert.strictEqual(y, 1);
|
|
|
|
}
|
2018-03-17 20:49:09 +05:30
|
|
|
bench.end(n);
|
2016-04-15 09:25:58 -07:00
|
|
|
}
|
|
|
|
|
2018-03-17 20:49:09 +05:30
|
|
|
function runSwapDestructured(n) {
|
2020-01-24 18:12:49 +01:00
|
|
|
let x, y;
|
2016-04-15 09:25:58 -07:00
|
|
|
bench.start();
|
2020-01-24 18:12:49 +01:00
|
|
|
for (let i = 0; i < n; i++) {
|
2020-11-24 14:11:20 +01:00
|
|
|
x = 1;
|
|
|
|
y = 2;
|
2016-04-15 09:25:58 -07:00
|
|
|
[x, y] = [y, x];
|
|
|
|
assert.strictEqual(x, 2);
|
|
|
|
assert.strictEqual(y, 1);
|
|
|
|
}
|
2018-03-17 20:49:09 +05:30
|
|
|
bench.end(n);
|
2016-04-15 09:25:58 -07:00
|
|
|
}
|
|
|
|
|
2018-03-17 20:49:09 +05:30
|
|
|
function main({ n, method }) {
|
2017-12-30 03:59:27 +01:00
|
|
|
switch (method) {
|
2016-04-15 09:25:58 -07:00
|
|
|
case 'swap':
|
2018-03-17 20:49:09 +05:30
|
|
|
runSwapManual(n);
|
2016-04-15 09:25:58 -07:00
|
|
|
break;
|
|
|
|
case 'destructure':
|
2018-03-17 20:49:09 +05:30
|
|
|
runSwapDestructured(n);
|
2016-04-15 09:25:58 -07:00
|
|
|
break;
|
|
|
|
default:
|
2018-01-23 13:18:30 +01:00
|
|
|
throw new Error(`Unexpected method "${method}"`);
|
2016-04-15 09:25:58 -07:00
|
|
|
}
|
|
|
|
}
|