Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
14
rated 0 times [  20] [ 6]  / answers: 1 / hits: 20553  / 10 Years ago, sun, july 20, 2014, 12:00:00

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


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


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


More From » performance

 Answers
5
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).


[#70132] Friday, July 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;