Is swapping variables by array destructuring efficient?

自闭症网瘾萝莉.ら 提交于 2019-12-06 05:47:11

问题


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.



来源:https://stackoverflow.com/questions/40943709/is-swapping-variables-by-array-destructuring-efficient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!