Sukhanov Niсkolay Sukhanov Niсkolay - 11 months ago 93
Javascript Question

Javascript TypedArray performance

Why are TypedArrays not faster then usual arrays? I want to use precalc values for CLZ(compute leading zeros function). And i don't want they interpreting as usual objects?

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.

Answer Source
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).