A while ago I've made a simple script in Javascript that tested how much time it takes to add elements to arrays. I've used 3 different methods: array.push(), array[array.length] and array[x] where x is the counter in the for loop. These results were stored and drawn to a simple graph using canvas. The script could basically run forever, taking the average times for every cycle.

After a few hours I started to notice something odd in the graph. the array.push() method had a pretty 'random' spike in the time it took to add all the elements. That by itself isn't too strange, but what was strange is that after adding even more elements with push, the total time went down again.

When the time increases, we're at about 96.000 elements. When the time decreases again, we're hitting 107.000 elements. The total time exceeds the spike again after about 183.000 elements. The other methods also have small spikes at some points, but not as big as the push spike.

There's a screenshot of what it looked like after 364 tests.

X axis is element count, Y axis is time

And for those whom want to see the code or run it for themselves: JSFiddle link

Why does this happen? What could cause the sudden increase and decrease in time?

  • It seems to only happen with the Crome JS engine. FF and IE are more consistent (IE after 7 runs). So than the question arises, why does the Chrome JS engine have such a 'hickup' while the others are more consistent? – Mathlight Jul 22 '16 at 7:09

Take a look at this article.

Javascript array memory management

It is similar to .NET memory handling in lists. You always want to set the initial size of a list (or any other collection, for that matter) to avoid suboptimal behavior from performance and from memory usage point of view.

  • That is a very interesting post, thank you! – Mathlight Jul 22 '16 at 7:19

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.