Appealing to non-exists element of array, reduces the performance very much

后端 未结 1 1226
挽巷
挽巷 2021-01-15 01:01

Made an observation - appealing to non-exists element of array, reduces the performance very much. It’s visibly on long loops. Why it happens?

Example:



        
相关标签:
1条回答
  • 2021-01-15 01:30

    This is most likely because the JavaScript engine is allocating the space for elements 0 through i in the empty array. When the array is filled the JS engine simply accesses the element and returns its value. In the empty case the engine prepares for a value to be set in that spot in the array, which requires allocating the space for that element.

    Running your sample code in Chrome 30 with the Task Manager open I observed a 10k spike in memory usage by the page during the second step (iterating over the empty array). This space was quickly freed afterwards as the engine realized the space wasn't being used.

    0 讨论(0)
提交回复
热议问题