Javascript TypedArray性能 [英] Javascript TypedArray performance

查看:264
本文介绍了Javascript TypedArray性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么TypedArrays不能比普通数组快?我想为CLZ使用预计算值(计算前导零函数).而且我不希望他们将其解释为通常的对象吗?

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

准备代码:

 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 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];

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性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆