本文翻译自:Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop
In order to duplicate an array in JavaScript: which of the following is faster to use? 为了在JavaScript中复制数组,请使用以下哪项更快?
Slice method 切片方法
var dup_array = original_array.slice();
For
loop For
循环
for(var i = 0, len = original_array.length; i < len; ++i)
dup_array[i] = original_array[i];
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. 我知道这两种方法都只能进行浅表复制 :如果original_array包含对对象的引用,则不会克隆对象,但只会复制引用,因此两个数组都将引用相同的对象。 But this is not the point of this question. 但这不是这个问题的重点。
I'm asking only about speed. 我只问速度。
#1楼
参考:https://stackoom.com/question/GgzE/在JavaScript中复制数组的最快方法-切片与-for-循环
#2楼
There are at least 5 (!) ways to clone an array: 至少有5种 (!)克隆数组的方法:
- loop 环
- slice 切片
- Array.from() Array.from()
- concat 康卡特
- spread operator (FASTEST) 点差算子(FASTEST)
There has been a huuuge BENCHMARKS thread , providing following information: 有一个很棒的BENCHMARKS线程 ,提供以下信息:
for blink browsers
slice()
is the fastest method,concat()
is a bit slower, andwhile loop
is 2.4x slower. 对于眨眼的浏览器,slice()
是最快的方法,concat()
慢一点,while loop
慢2.4倍。for other browsers
while loop
is the fastest method, since those browsers don't have internal optimizations forslice
andconcat
. 对于其他浏览器,while loop
是最快的方法,因为这些浏览器没有对slice
和concat
进行内部优化。
This remains true in Jul 2016. 2016年7月仍然如此。
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 loop 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);
slice 切片
n = 1000*1000;
start = + new Date();
a = Array(n);
b = a.slice();
console.log(new Date() - start);
Please note that these methods will clone the Array object itself, array contents however are copied by reference and are not deep cloned. 请注意,这些方法将克隆Array对象本身,但是数组内容是通过引用复制的,因此不会进行深度克隆。
origAr == clonedArr //returns false
origAr[0] == clonedArr[0] //returns true
#3楼
Technically slice
is the fastest way. 从技术上讲, slice
是最快的方法。 However , it is even faster if you add the 0
begin index. 但是 ,如果添加0
开始索引,它甚至更快。
myArray.slice(0);
is faster than 比...快
myArray.slice();
http://jsperf.com/cloning-arrays/3 http://jsperf.com/cloning-arrays/3
#4楼
There is a much cleaner solution: 有一个更清洁的解决方案:
var srcArray = [1, 2, 3];
var clonedArray = srcArray.length === 1 ? [srcArray[0]] : Array.apply(this, srcArray);
The length check is required, because the Array
constructor behaves differently when it is called with exactly one argument. 长度检查是必需的,因为当仅使用一个参数调用Array
构造函数时,其行为会有所不同。
#5楼
深度克隆数组或对象的最简单方法:
var dup_array = JSON.parse(JSON.stringify(original_array))
#6楼
es6方式呢?
arr2 = [...arr1];