Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
scroll top