Why push method is significantly slower than putting values via array indices in Javascript

前端 未结 3 450
攒了一身酷
攒了一身酷 2020-12-15 21:39

I pretty don\'t understand why this test :

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

Shows that

 a.push(Math.random());
3条回答
  •  佛祖请我去吃肉
    2020-12-15 22:03

    Could you explain why this is the case?

    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.

提交回复
热议问题