Javascript最快的方式来复制一个Array - slice vs for loop [英] Javascript fastest way to duplicate an Array - slice vs for loop
问题描述
为了在Javascript中复制数组,
任何人都知道(也许测试)如果使用更快:
切片方法:
var dup_array = original_array.slice
或 For循环:
for(var i = 0,len = original_array.length; i dup_array [i] = original_array [i]
更新:(为了澄清自己)两个方法只做一个浅拷贝:如果original_array包含对对象的引用,对象不会被克隆,但只有引用将被复制,因此两个数组都将引用相同的对象。
但这不是这个问题的要点。
我只是问速度。
克隆数组至少有 5 (!)种方法:
- 循环
- 切片
- Array.from()
-
- 传播运算符等(很慢,现在忘记了)
提供了以下信息: BENCHMARKS主题,提供以下信息:
- code 有点慢,
-
其他浏览器
while
是最快的方法,因为这些浏览器没有内部优化切片
和concat
。
while循环
慢2.4倍。 这在2016年7月仍然如此。
以下是简单的脚本,您可以复制 - 粘贴到浏览器的控制台,图片。
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);
In order to duplicate an Array in Javascript,
does anyone know (and maybe tested) if it's faster to use:
Slice method:
var dup_array = original_array.slice();
or For loop:
for(var i = 0, len = original_array.length; i < len; ++i)
dup_array[i] = original_array[i];
UPDATE: (just to clarify myself) 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 therefore both arrays will have references to the same objects. But this is not the point of this question.
I'm asking only about speed.
There are at least 5 (!) ways to clone an array:
- loop
- slice
- Array.from()
- concat
- spread operator, etc. (so slow, forget it for now)
There has been a huuuge BENCHMARKS thread, providing following information:
for blink browsers
slice()
is the fastest method,concat()
is a bit slower, andwhile loop
is 2.4x slower.for other browsers
while loop
is the fastest method, since those browsers don't have internal optimizations forslice
andconcat
.
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 loop
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);
这篇关于Javascript最快的方式来复制一个Array - slice vs for loop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!