Is swapping variables by array destructuring effic

2020-07-18 07:52发布

问题:

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]

回答1:

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.