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

查看:236
本文介绍了在处理数组时,使用扩展语法(...)和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,

方法1:

pets.push.apply(pets,wishlist)

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

方法2:

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天全站免登陆