在 JavaScript 中复制数组的最快方法 - 切片与“for"循环 [英] Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop
问题描述
为了在 JavaScript 中复制数组:以下哪个使用起来更快?
In order to duplicate an array in JavaScript: Which of the following is faster to use?
var dup_array = original_array.slice();
For
循环
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.
我只问速度.
推荐答案
至少有 6 (!) 种方法来克隆数组:
There are at least 6 (!) ways to clone an array:
- 循环
- 切片
- Array.from()
- 连接
- 展开运算符(最快)
- map
A.map(function(e){return e;});
有一个huuuge BENCHMARKS thread,提供以下信息:
There has been a huuuge BENCHMARKS thread, providing following information:
对于blink 浏览器来说
slice()
是最快的方法,concat()
有点慢,而while 循环
慢了 2.4 倍.
for blink browsers
slice()
is the fastest method,concat()
is a bit slower, andwhile loop
is 2.4x slower.
对于其他浏览器 while loop
是最快的方法,因为这些浏览器没有对 slice
和 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屋!