function tempSwap(array) {
const length = array.length;
const swap1 = Math.floor(Math.random() * length);
const swap2 = Math.floor(Math.random() * length);
const temp = array[swap1];
array[swap1] = array[swap2];
array[swap2] = array[temp];
}
function destructuringSwap(array) {
const length = array.length;
const swap1 = Math.floor(Math.random() * length);
const swap2 = Math.floor(Math.random() * length);
return [
array[swap1],
array[swap2]
] = [
array[swap2],
array[swap1]
];
}
function xorSwap(array) {
const length = array.length;
const swap1 = Math.floor(Math.random() * length);
const swap2 = Math.floor(Math.random() * length);
array[swap1] ^= array[swap2];
array[swap2] ^= array[swap1];
array[swap1] ^= array[swap2];
}
tempSwap(new Array(10));
destructuringSwap(new Array(10));
tempSwap(new Array(100));
destructuringSwap(new Array(100));
tempSwap(new Array(1000));
destructuringSwap(new Array(1000));
xorSwap(new Array(10));
xorSwap(new Array(100));
xorSwap(new Array(1000));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Length 10 temp swap | |
Length 10 destructuring swap | |
Length 100 temp swap | |
Length 100 destructuring swap | |
Length 1000 temp swap | |
Length 1000 destructuring swap | |
Length 10 xor swap | |
Length 100 xor swap | |
Length 1000 xor swap |
Test name | Executions per second |
---|---|
Length 10 temp swap | 33708244.0 Ops/sec |
Length 10 destructuring swap | 46224932.0 Ops/sec |
Length 100 temp swap | 17193668.0 Ops/sec |
Length 100 destructuring swap | 19618372.0 Ops/sec |
Length 1000 temp swap | 2885102.8 Ops/sec |
Length 1000 destructuring swap | 2962069.2 Ops/sec |
Length 10 xor swap | 32990530.0 Ops/sec |
Length 100 xor swap | 16357835.0 Ops/sec |
Length 1000 xor swap | 3115000.0 Ops/sec |
Measuring the performance of different approaches to array item swapping in JavaScript can be a complex task.
What is being tested?
The provided benchmark test case compares three approaches to swapping two elements in an array:
Options being compared:
The benchmark test case compares the execution speed of these three approaches for different array sizes (10, 100, and 1000).
Pros and cons of each approach:
Other considerations:
Overall, the benchmark highlights the importance of considering different approaches to array item swapping in JavaScript, especially when working with large datasets or performance-critical code.