
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.
Results
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:
1 |
var myArray = []; |
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.
1 |
var myArray = new Array(500); |
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.
1 2 |
var myArray = []; myArray.length = 1000; |
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.
Latest posts by Travis Payton (see all)
- Adventures with Sendmail - January 3, 2019
- Django – selective restore of DB dump - April 11, 2016
- Cord Cutting The Geek Way – Watch your favorite TV shows for free, anytime, anywhere! - January 20, 2016
5 comments for “High Performance JavaScript – Array Creation & Population”