Javascript TypedArray performance

前端 未结 3 1797
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 02:44

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?

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 03:36

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

提交回复
热议问题