ES6 supports array destructuring which could be used to swap variables in succinct syntax like below, but is this efficient and suggested in performance sensitive code as array processing? Because it seems a new temporary array is needed to complete this operation.
[a, b] = [b, a]
Let's test !
let a = 42
let b = 69
console.log("for 2000000 iterations");
console.time("deconstruct")
for(let i=2000000; i>=0; --i)
[a, b] = [b, a];
console.timeEnd("deconstruct")
console.time("classical")
for(let i=2000000; i>=0; --i) {
let tmp = a
a = b
b = tmp
}
console.timeEnd("classical")
So it not seems to be the better way to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With