High Performance JavaScript – Array Creation & Population

Preallocating arrays in Javascript is about 65% faster than not!
JavaScript Array Performance in Chrome V8 using a size of 10,000 elements

JavaScript Arrays

Arrays in JavaScript are very easy to use and there are some simple tricks to make them perform at peak efficiency.  Testing shows that the recommended standard method for declaring arrays in JavaScript ( var a = [];) has pretty poor performance when compared to using the less popular alternative ( var a = new Array(100);).

Most people argue that the performance difference is negligible and the benefits of the standard method outweigh any performance gains possible. However, I am working on developing a high performance Neural Network Library in JavaScript, and the more evaluations per second I can get through my network the better!

Creating and evaluating neural networks is mostly composed of reading and writing values to arrays, so benchmarking array performance has been the first step towards optimizing the library.

I used JSPerf.com to do these early benchmarks.  In another post I will use chrome’s built-in JavaScript profiler to do more in-depth benchmarks of the Neural Network library once the library is more complete.


JavaScript Array Allocation

According to a discussion on stack overflow, there is no real good reason to use anything other than the standard method of creating an array in JavaScript:

Its more readable, the overhead is small, and it leaves all the memory management to the JavaScript engine.  However, allocating all the space at once instead of in increments during the filling process is generally quicker.

This method is generally frowned upon as its easier to make mistakes and its “harder to read”. In fact, w3schools says to avoid it outright! (see the When to Use Arrays? section.) However, for my Neural Network this method is way more efficient and faster!

If you want to test it on your machine / browser here is the link:  http://jsperf.com/preallocating-array/8

Large JavaScript Arrays in Chrome V8

It turns out that V8 does a neat trick internally with an object’s hidden class when it sees a large array length.  It switches from an array of unsigned integers, to a sparse array (i.e., map).  In order to force this optimization you can manually set the length property.

This is ONLY faster when working with large arrays: about 1000+.  For smaller arrays it is only slightly slower, if not the same speed.

If you want to test this on your machine / browser here is the link: http://jsperf.com/preallocating-array/9


In the Next Post I will benchmark the fastest ways to read and write values in JavaScript arrays.

Travis Payton
Follow Me

  5 comments for “High Performance JavaScript – Array Creation & Population

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: