准备代码: 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; };测试1:sum = arr[(Math.random() * 0x10000) | 0];测试2:sum = Uint32[(Math.random() * 0x10000) | 0]; PS可能是我的性能测试无效,请随时纠正我.解决方案 var buffer = new ArrayBuffer(0x10000);var Uint32 = new Uint32Array(buffer);与以下内容不同:var Uint32 = new Uint32Array(0x10000);不是因为新的ArrayBuffer(总是得到一个数组缓冲区:在两种情况下都请参见Uint32.buffer),而是由于length参数:使用ArrayBuffer每个元素有1个字节,使用Uint32Array每个元素有4个字节. 因此,在第一种情况下(以及在您的代码中),Uint32.length = 0x1000/4,循环超出了4的3倍.但是可悲的是,您永远不会得到错误,只有糟糕的性能.使用'new ArrayBuffer',您必须像这样声明Uint32:var buffer = new ArrayBuffer(0x10000 * 4);var Uint32 = new Uint32Array(buffer);请参见具有(0x10000)的jsperf 和具有(0x10000 * 4)的jsperf .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? http://jsperf.com/array-access-speed-2/2Preparation 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];PS May be my perf tests are invalid feel free to correct me. 解决方案 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). 这篇关于Javascript TypedArray性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-16 07:36