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

前端 未结 3 452
攒了一身酷
攒了一身酷 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:18

    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.

提交回复
热议问题