复制对象数组的方式哪种更快:切片还是克隆?
我需要发送值而不是对数组的引用。对于这个问题,我得到了 2-3 个有效答案。第一个是使用切片,第二个(第三个类似)是使用克隆或制作我自己的克隆函数。
从(非常)快速的测试来看,slice 似乎更快(在 100,000 个元素的数组上进行测试)。但我对此没有任何解释。
谁能澄清切片是否以及为什么更快?
This is related to: How do I pass the value instead of the refererence of an array?
I need to send the value instead of reference to an array. To that question I got 2-3 valid answers. One was use slice, second (and third was similar) was to use clone or make my own clone function.
From a (very) quick test, it seems like slice was faster (tested on a 100,000 elements array). But I don't have any explanation for that.
Can anyone clarify if and why is slice faster?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该答案中提出的
clone
函数非常通用(也很差;从来没有、永远、曾经向Object.prototype
添加可枚举属性>,还有其他问题),并且是用 JavaScript 实现的。相比之下,slice
答案使用 JavaScript 引擎的内置函数,可以用高度优化的机器代码编写。 (或者当然不是。)The
clone
function presented in that answer is very general (also quite poor; never, ever, ever add enumerable properties toObject.prototype
, and there are other issues as well), and is implemented in JavaScript. In contrast, theslice
answer uses the JavaScript engine's built-in function, which can be written in highly optimized machine code. (Or not, of course.)