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);
[
array[swap1],
array[swap2]
] = [
array[swap2],
array[swap1]
];
}
tempSwap(new Array(10));
destructuringSwap(new Array(10));
tempSwap(new Array(100));
destructuringSwap(new Array(100));
tempSwap(new Array(1000));
destructuringSwap(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 |
Test name | Executions per second |
---|---|
Length 10 temp swap | 17986974.0 Ops/sec |
Length 10 destructuring swap | 24715506.0 Ops/sec |
Length 100 temp swap | 10699824.0 Ops/sec |
Length 100 destructuring swap | 13495602.0 Ops/sec |
Length 1000 temp swap | 2290509.5 Ops/sec |
Length 1000 destructuring swap | 2260521.2 Ops/sec |
This benchmark compares two different methods for swapping items in an array: using a temporary variable and using array destructuring. The primary focus is on their performance at different array sizes: 10, 100, and 1000 elements.
Temporary Variable Swap (tempSwap
):
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] = temp;
}
Destructuring Swap (destructuringSwap
):
function destructuringSwap(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]];
}
Temporary Variable Swap:
Destructuring Swap:
From the benchmark results, the following observations can be made:
For arrays of length 10:
For arrays of length 100:
For arrays of length 1000:
Browser and Version Compatibility: The performance can vary depending on the JavaScript engine of the browser being used. The result gathered was specific to Chrome 135, and different browsers or even different versions might yield different performance metrics.
Function Overhead: Both functions introduce some overhead due to the way they are called and how random indices are generated. If working with small arrays frequently, this setup might introduce inefficiencies that would not be noticeable in larger operations where the actual swapping takes longer than the overhead.
This benchmark provides valuable insight into how two common techniques to swap elements can be tested against one another, helping programmers choose the right method based on array size and compatibility needs.