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

只谈情不闲聊 提交于 2019-11-29 03:58:05
Bergi

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.

That's simply because Google decided to put more work into optimising array indexing than optimising the push method in Chrome.

If you look at the test results now that a few more people have tried it, you see that the performance differes quite a lot between different browsers, and even between different versions of the same browser.

Nowadays browsers compile the Javascript code, which means that the browser turns the code into something that is much faster to run that interpreted Javascript. What the compiler does with the code determines how different ways of doing things performs. Different compilers optimise certain things better, which gives the different preformances.

Because the .push() is a function call and the other is direct assignment. Direct assignment is always faster.

Remember that in javascript, arrays are objects like everything else. This means you can assign properties directly to them.

In the special case of arrays, they have a built-in length property that gets update behind the scenes (and lots of other optimizations under the hood, but that's not important right now).

In a regular object, you can do this but its not an array:

var x = {
   0: 'a',
   1: 'b',
   2: 'c'
};

However, since arrays and hashes are both objects, this is equivalent.

   var x = [
      'a',
      'b',
      'c'
   ];

Since x is an array in the second case, length is automatically calculated and available.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!