ArrayBufferView 构造函数中的奇怪限制

发布于 2024-12-06 19:13:30 字数 673 浏览 0 评论 0原文

TypedArray 规范 规定 ArrayBufferView 可以通过这种方式创建:

TypedArray(ArrayBuffer buffer, 
           optional unsigned long byteOffset, optional unsigned long length)

但是,第二个参数 byteOffset 有一个限制:

给定的 byteOffset 必须是元素大小的倍数 特定类型,否则会引发异常。

这意味着我们无法使用两字节视图的奇数偏移量,例如:

var view1  = new Uint8Array([0, 1, 2, 3]),
    view2 = new Uint16Array(view1.buffer, 1, 1);

因此,即使 [1,2] 可以正确转换为 Uint16,我也无法以这种方式访问​​这些元素。 byteOffset 限制似乎显着降低了 ArrayBufferView 的灵活性。

有谁知道为什么施加这个限制?

The TypedArray specification states that an ArrayBufferView may be created this way:

TypedArray(ArrayBuffer buffer, 
           optional unsigned long byteOffset, optional unsigned long length)

However, the second parameter, byteOffset, has a limitation:

The given byteOffset must be a multiple of the element size of the
specific type, otherwise an exception is raised.

This means we cannot work with odd offsets for two-byte views, such as:

var view1  = new Uint8Array([0, 1, 2, 3]),
    view2 = new Uint16Array(view1.buffer, 1, 1);

So, even though [1,2] could be correctly converted into Uint16, I can't access those elements that way.
The byteOffset limitation seems to significantly decrease ArrayBufferView's flexibility.

Does anybody know why this limitation was imposed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

习ぎ惯性依靠 2024-12-13 19:13:30

施加此限制是为了保持类型化数组视图(例如 Uint16Array 和 Float32Array)的最大性能。这些类型旨在对机器自然对齐的数据进行操作。支持未对齐的负载要么会导致快速情况的速度降低到令人无法接受的程度,要么会导致性能“悬崖”,程序在大多数情况下都会运行得很快,除非它们减慢了很大的因素。

DataView 旨在支持单个数据元素的未对齐加载和存储,特别是用于处理网络或磁盘 I/O 的情况,其中文件格式可能没有任何对齐限制。

This restriction was imposed in order to maintain maximum performance for the typed array views such as Uint16Array and Float32Array. These types are designed to operate on data in the machine's natural alignment. Supporting unaligned loads would either slow down the fast case unacceptably, or lead to performance "cliffs" where programs would mostly run fast, except when they slowed down by a large factor.

DataView is designed to support unaligned loads and stores of single elements of data, specifically to handle the case of networking or disk I/O, where file formats may not have any alignment restrictions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文