Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is swapping variables by array destructuring efficient?

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]
like image 756
Thomson Avatar asked Oct 18 '22 21:10

Thomson


1 Answers

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.

like image 154
NatNgs Avatar answered Oct 21 '22 08:10

NatNgs