在JavaScript中复制数组的最快方法 - 切片与'for'循环 [英] Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

查看:203
本文介绍了在JavaScript中复制数组的最快方法 - 切片与'for'循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了在JavaScript中复制数组:以下哪个更快使用?

In order to duplicate an array in JavaScript: which of the following is faster to use?

var dup_array = original_array.slice();



对于循环



For loop

for(var i = 0, len = original_array.length; i < len; ++i)
   dup_array[i] = original_array[i];






我知道两种方式只做浅拷贝:如果original_array包含对象的引用,则不会克隆对象,但只会复制引用,因此两个数组都将引用相同的对象。
但这不是这个问题的重点。


I know both ways do only a shallow copy: if original_array contains references to objects, objects won't be cloned, but only the references will be copied, and therefore both arrays will have references to the same objects. But this is not the point of this question.

我只询问速度。

推荐答案

至少有 5 (!)克隆数组的方法:

There are at least 5 (!) ways to clone an array:


  • loop

  • slice

  • Array.from()

  • concat

  • 传播运营商等(这么慢,暂时不要忘记)

  • loop
  • slice
  • Array.from()
  • concat
  • spread operator, etc. (so slow, forget it for now)

有一个huuuge BENCHMARKS主题,提供以下信息:

There has been a huuuge BENCHMARKS thread, providing following information:


  • 闪烁浏览器 slice()是最快的方法, concat()稍慢,而,而循环慢2.4倍。

  • for blink browsers slice() is the fastest method, concat() is a bit slower, and while loop is 2.4x slower.

其他浏览器 while循环是最快的方法,因为这些浏览器没有内部优化对于切片 concat

for other browsers while loop is the fastest method, since those browsers don't have internal optimizations for slice and concat.

2016年7月仍然如此。

This remains true in Jul 2016.

以下是简单的脚本,您可以将其复制粘贴到浏览器的控制台并运行几次以查看图片。它们输出毫秒,越低越好。

Below are simple scripts that you can copy-paste into your browser's console and run several times to see the picture. They output milliseconds, lower is better.

while循环

n = 1000*1000;
start = + new Date();
a = Array(n); 
b = Array(n); 
i = a.length;
while(i--) b[i] = a[i];
console.log(new Date() - start);

切片

n = 1000*1000;
start = + new Date();
a = Array(n); 
b = a.slice();
console.log(new Date() - start);

请注意,这些方法将克隆Array对象本身,但数组内容是通过引用复制的,并且是没有深度克隆。

Please note that these methods will clone the Array object itself, array contents however are copied by reference and are not deep cloned.

origAr == clonedArr //returns false
origAr[0] == clonedArr[0] //returns true

这篇关于在JavaScript中复制数组的最快方法 - 切片与'for'循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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