处理数组时使用扩展语法 (...) 和 push.apply 的区别 [英] Difference between using a spread syntax (...) and push.apply, when dealing with arrays

查看:19
本文介绍了处理数组时使用扩展语法 (...) 和 push.apply 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组,

const pets = ["dog", "cat", "hamster"]

const wishlist = ["bird", "snake"]

我想将wishlist附加到pets,这可以使用两种方法来完成,

I want to append wishlist to pets, which can be done using two methods,

方法一:

pets.push.apply(pets,wishlist)

结果是:[ 'dog', 'cat', 'hamster', 'bird', 'snake' ]

方法二:

pets.push(...wishlist)

这也会导致:[ 'dog', 'cat', 'hamster', 'bird', 'snake' ]

当我处理较大的数据时,这两种方法在性能方面有区别吗?

Is there is a difference between these two methods in terms of performance when I deal with larger data?

推荐答案

Function.prototype.apply 和扩展语法在应用于大数组时都可能导致堆栈溢出:

Both Function.prototype.apply and the spread syntax may cause a stack overflow when applied to large arrays:

let xs = new Array(500000),
 ys = [], zs;

xs.fill("foo");

try {
  ys.push.apply(ys, xs);
} catch (e) {
  console.log("apply:", e.message)
}

try {
  ys.push(...xs);
} catch (e) {
  console.log("spread:", e.message)
}

zs = ys.concat(xs);
console.log("concat:", zs.length)

使用 Array.prototype.concat 代替.除了避免堆栈溢出,concat 还具有避免突变的优点.突变被认为是有害的,因为它们会导致微妙的副作用.

Use Array.prototype.concat instead. Besides avoiding stack overflows concat has the advantage that it also avoids mutations. Mutations are considered harmful, because they can lead to subtle side effects.

但这不是教条.如果您在函数作用域内执行更改以提高性能并减少垃圾收集,您可以执行更改,只要它们在父作用域中不可见即可.

But that isn't a dogma. If you are wihtin a function scope and perform mutations to improve performance and relieve garbage collection you can perform mutations, as long as they aren't visible in the parent scope.

这篇关于处理数组时使用扩展语法 (...) 和 push.apply 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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