本文介绍了为什么 push 方法比通过 Javascript 中的数组索引放置值慢得多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很不明白为什么要进行此测试:

.

除此之外,对 push 的方法调用可能会有一些开销,与使用 for 循环的索引相比,确定当前数组长度可能需要更多时间.

通常有没有理由不使用push - 该方法正是为了该操作并使某些代码更易于阅读.虽然有些人认为一个版本比另一个版本更快,但两者都在浏览器中进行了同样的优化.请参阅 为什么 array.push 有时比 array[n] 快 =值?在添加到数组时使用 push 方法或 .length? - 结果差异如此之大,以至于其实无关.使用更容易理解的内容.

I pretty don't understand why this test :

http://jsperf.com/push-method-vs-setting-via-key

Shows that

 a.push(Math.random());

is over ten times slower than

 a[i] = Math.random();

Could you explain why this is the case ? What magic "push" do that make it so slow ? (or so slow compared to other valid method of doing that).

EDIT

NOTE: The push test is biased. I increase size of the array every iteration! Read carefully accepted answer!

解决方案

Because your test is flawed. The push does always append to the existing a array making it much larger, while the second test does only use the first 1000 indices.Using the setup is not enough here, you would have to reset the a array before every for-loop: http://jsperf.com/push-method-vs-setting-via-key/3.

Apart from that, the method call to push might have a little overhead, and determining the current array length might need additional time compared to using the index of the for-loop.

Usually there is no reason not to use push - the method is there for exactly that operation and makes some code easier to read. While a few people think one version is faster than the other, both are equally optimized in browsers. See Why is array.push sometimes faster than array[n] = value? and Using the push method or .length when adding to array? - results vary so wide that it's actually irrelevant. Use what is better to understand.

这篇关于为什么 push 方法比通过 Javascript 中的数组索引放置值慢得多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:47