的Javascript最快的方式复制一个阵列 - 切片VS循环 [英] Javascript fastest way to duplicate an Array - slice vs for loop

查看:143
本文介绍了的Javascript最快的方式复制一个阵列 - 切片VS循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了复制在Javascript数组,

In order to duplicate an Array in Javascript,

没有人知道(也许测试),如果它的速度更快的使用方法:

does anyone know (and maybe tested) if it's faster to use:

切片方法:

var dup_array = original_array.slice();

有关循环:

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


更新:(只是为了澄清自己)我知道,这两个方面做的只有浅拷贝:如果original_array包含对象的引用,对象将不会被克隆,但只引用将被复制,因此两个阵列将有相同的对象的引用。
但是,这不是这个问题的地步。


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.

我问大约只有速度。

推荐答案

有至少 4 以克隆阵列主要途径(!):

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


  • 循环

  • 构造

  • 片/接头

  • CONCAT

有超过14分 - 的方式。浏览基准线程他们。许多holywars被打,选择其中最好的一个... Benchmark是唯一的判断:

There are over 14 sub - ways. Browse the benchmark thread for them. Many holywars were fought to choose the best one among them... Benchmark is the only judge:

奇怪地看到,火狐25,Safari浏览器6,Safari浏览器适用于iOS 7和IE 11还处于石器时代,并使用,而循环是最快的方式,为他们。我猜想在使用本机方法一步克隆是preferable因为他们是用C /汇编和开放的内部优化(它们应该使用直接内存块复制)。这是在V8已经实现,我predict,它应该由其他人在未来实现。

Strange to see that Firefox 25, Safari 6, Safari for iOS 7 and IE 11 are still in the stone age and using a while loop is the fastest way for them. I suppose cloning in a single step using native methods is preferable because they are written in C / Assembler and open for internal optimizations (they should use direct memory block copying). This is already implemented in V8 and I predict that it should be implemented by others in future.

快速的回答是:

 var b = a.slice();

使用 CONCAT 是正确的为好。

这个答案变得过时快。使用基准来检查的实际情况

这篇关于的Javascript最快的方式复制一个阵列 - 切片VS循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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