Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

长度对 new Array 性能的影响 #68

Open
leeenx opened this issue Sep 14, 2017 · 0 comments
Open

长度对 new Array 性能的影响 #68

leeenx opened this issue Sep 14, 2017 · 0 comments

Comments

@leeenx
Copy link
Contributor

leeenx commented Sep 14, 2017

在未测试之前我做个猜测,长度对 new Array 的性能几乎没有影响,即 new Array(1000) 与 new Array(100000) 在性能上应该是一样的。

为什么我这样觉得?
因为我觉得如果是开辟一段内存给数组的话不需要有遍历这段内存。如果长度对 new Array 有影响的话,只能说明 浏览器在创建数组的时候会遍历一次内存并把内存的数据清空。

数组长度对 new Array 性能的影响

写一个测试用例:https://jsperf.com/diff-length-array
图示

在我的 chrome 测试的结果如上。结果跟我预计的相反:创建数组时,数组长度与性能成反比。没想到 javascrippt 在创建数组时需要对整个数组进行值的重置。

再看一下这个用例在 safari 下的表现:
图示

webkit 内核的表现还是差不多的。上面的性能的差异近似于数组长度的倍数差异。为了更全面的验证长度对创建数组的影响,我又追加了 array.length = n 测试代码,结果数据大同小异如下:
图示

数组长度对concat性能的影响

作为思维的延伸,我其实也想知道数组长度对 concat 有没有影响。这次我觉得是有影响的,并且与new Array是一样的。
以下是一个测试用例:https://jsperf.com/2017-array-concat-perf

我本地的测试结果如下:
图示

这次测试结果跟我的预计一样。如果跟 https://jsperf.com/diff-length-array 这个用例的数据做对比可以发现当前数据是上一个用例的一半。因为 concat 操作前有 new Array 的操作,所以可以得到一个结论:concat 复制一个数组的能耗与new Array一个数组相当。

总结

截图上的性能数据表明创建数组和复制数组对性能的消耗很大。所以我的总结主要是两点:

  1. 创建和复制数组烧性能
  2. 创建数组的能耗等于复制数组的能耗

要避免频繁复制/创建数组。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant