问题描述
什么时候对浏览器应用程序使用 Float32Array
而不是标准的 JavaScript Array
有意义?
When does it make sense to use a Float32Array
instead of a standard JavaScript Array
for browser applications?
这个性能测试显示Float32Array
在一般,较慢 - 如果我理解正确的话,标准 Array
将数字存储为 64 位 - 所以在精度上没有优势.
This performance test shows Float32Array
to be, in general, slower - and if I understand correctly a standard Array
stores numbers as 64bit - so there is no advantage in precision.
除了任何可能的性能损失之外,Float32Array
还具有可读性的缺点 - 必须使用构造函数:
Aside from any possible performance hit, Float32Array
also has the disadvantage of readability - having to use a constructor:
a = new Float32Array(2);
a[0] = 3.5;
a[1] = 4.5;
改为数组字面量
a = [3.5, 4.5];
我之所以这么问是因为我正在使用默认为 Float32Array
的库 glMatrix - 并且想知道是否有任何理由我不应该强迫它使用 Array
相反,这将允许我使用数组文字.
I'm asking this because I'm using the library glMatrix which defaults to Float32Array
- and wondering if there's any reason I shouldn't force it to use Array
instead which will allow me to use array literals.
推荐答案
我给 glMatrix
的开发人员发了电子邮件,下面的回答包括他的评论(第 2 点和第 3 点):
I emailed the developer of glMatrix
and my answer below includes his comments (points 2 & 3):
使用
Array
创建新对象通常比使用Float32Array
更快.小阵列的增益很显着,但大阵列的增益较小(取决于环境).
Creating a new object is generally quicker with
Array
thanFloat32Array
. The gain is significant for small arrays, but is less (environment dependent) with larger arrays.
从TypedArray
(例如Float32Array
)访问数据通常比从普通数组更快,这意味着大多数使用 TypedArrays 的数组操作(除了创建新对象)更快.
Accessing data from a TypedArray
(eg. Float32Array
) is often faster than from a normal array, which means that most array operations (aside from creating a new object) are faster with TypedArrays.
正如@emidander 所述,glMatrix
主要是为 WebGL 开发的,它要求向量和矩阵作为 Float32Array
传递.因此,对于 WebGL 应用程序,任何性能测量都需要包含从 Array
到 Float32Array
的潜在成本高昂的转换.
As also stated by @emidander, glMatrix
was developed primarily for WebGL, which requires that vectors and matrices be passed as Float32Array
. So, for a WebGL application, the potentially costly conversion from Array
to Float32Array
would need to be included in any performance measurement.
因此,毫不奇怪,最佳选择取决于应用程序:
So, not surprisingly, the best choice is application dependent:
如果数组通常很小,和/或对它们的操作次数很少,以至于构造函数时间占数组生命周期的很大一部分,请使用
Array
.
如果代码可读性和性能一样重要,那么使用 Array
(即使用 []
,而不是构造函数).
If code readability is as important as performance, then use Array
(i.e. use []
, instead of a constructor).
如果数组非常大和/或用于许多操作,则使用 TypedArray.
If arrays are very large and/or are used for many operations, then use a TypedArray.
对于 WebGL 应用程序(或其他需要类型转换的应用程序),使用 Float32Array
(或其他 TypedArray
).
For WebGL applications (or other applications that would otherwise require a type conversion), use Float32Array
(or other TypedArray
).
这篇关于何时在 JavaScript 中使用 Float32Array 而不是 Array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!