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:
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.