javascriptperformancetyped-arrays

Javascript TypedArray performance


Why are TypedArrays not as fast as regular arrays? I want to store some precalculated integer values, and I need the access to the array to be as fast as it can be.

http://jsperf.com/array-access-speed-2/2

Preparation code:

 Benchmark.prototype.setup = function() {
   var buffer = new ArrayBuffer(0x10000);
   var Uint32 = new Uint32Array(buffer);
   var arr = [];
   for(var i = 0; i < 0x10000; ++i) {
     Uint32[i] = (Math.random() * 0x100000000) | 0;
     arr[i] = Uint32[i];
   }
   var sum = 0;
 };

Test 1:

sum = arr[(Math.random() * 0x10000) | 0];

Test 2:

sum = Uint32[(Math.random() * 0x10000) | 0];

enter image description here

PS: May be my perf tests are invalid feel free to correct me.


Solution

  • var buffer = new ArrayBuffer(0x10000);
    var Uint32 = new Uint32Array(buffer);
    

    is not the same thing as:

    var Uint32 = new Uint32Array(0x10000);
    

    not because of the new ArrayBuffer (you always get an array buffer: see Uint32.buffer in both cases) but because of the length parameter: with ArrayBuffer you have 1 byte per element, with Uint32Array you have 4 bytes per element.

    So, in the first case (and in your code), Uint32.length = 0x1000/4 and your loops are out of bounds 3 out of 4 times. But sadly you will never get errors, only poor performances.

    Using new ArrayBuffer, you have to declare Uint32 like this:

    var buffer = new ArrayBuffer(0x10000 * 4);
    var Uint32 = new Uint32Array(buffer);
    

    See jsperf with (0x10000) and jsperf with (0x10000 * 4).