通过数组解构交换变量是否有效? [英] Is swapping variables by array destructuring efficient?

查看:96
本文介绍了通过数组解构交换变量是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ES6支持数组解构,该数组解构可用于以简洁的语法(如下所示)交换变量,但是这种高效和建议在对性能敏感的代码中作为数组处理来使用吗?因为似乎需要一个新的临时数组才能完成此操作.

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 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.

这篇关于通过数组解构交换变量是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆