These types of variable assignments are a common theme through all if not most programming languages. Each of them pose various performance, and readability issues.
I didn’t realize any of these performance issues of swapping until I tried running bubble sort with a large array. Bubble Sort is already a weak sorting algorithm (Time Complexity of O(N²)), but the way you swap the variables can make that that process take even longer.
function bubbleSort(array) {for(let i = 0; i < array.length; i++) {for(let j = i; j < array.length; j++) {if (array[i] > array[j]) {
//let temp = array\[i\];
//array\[i\] = array\[j\];
//array\[j\] = temp;
// Easy Swap #1 \[array\[i\], array\[j\]\] = \[array\[j\], array\[i\]\];
// Easy Swap #1A array\[j\] = \[array\[i\], array\[i\] = array\[j\]\]\[0\];
}}}return array;}
sorting([3,6,7,2,4,5,8,1,11,52,73,23,45,22,12,15,7,26,32,66])
After running these into a Benchmark:Test 1: Temp AssignmentTest 2: Destructuring Assignment
Temp assignment is much faster.
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!