6

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]
3
  • You may get some info on evaluation from the specification. Commented Dec 3, 2016 at 2:46
  • @Li357 The specification does not detail performance Commented Jan 26, 2018 at 15:12
  • @Bergi I was addressing the "it seems a new temporary array is needed to complete this operation" concern. Commented Jan 26, 2018 at 15:42

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

What results are you getting in which browser?
Ah ? It's works for me on Firefox 57 and Chrome; I get for 2000000 iterations - deconstruct: 22.460ms - classical: 3.980ms - function: 1.580ms. It's ES6 arrow function syntax in fact
Have you tried to actually swap two values with the "function" syntax? Sure it doesn't throw an error, but it does not have the expected result
Hum.. You're right, I did not expected this haha. Let's remove this case..
I let you run the test by yourself and get your own conclusions :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.