ArrayBufferView构造函数中的奇怪限制 [英] Strange limitation in ArrayBufferView constructor

查看:93
本文介绍了ArrayBufferView构造函数中的奇怪限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypedArray规范指出可以为此创建ArrayBufferView方式:

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

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

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

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

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

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

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

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?

推荐答案

施加此限制是为了保持类型化数组视图(例如Uint16Array和Float32Array)的最佳性能.这些类型旨在以机器的自然对齐方式对数据进行操作.支持未对齐的负载可能会使快速运行速度降低到令人无法接受的程度,或者导致性能悬崖",除非程序在很大程度上降低了运行速度,否则程序大多会快速运行.

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旨在支持未对齐的负载和单个数据元素的存储,特别是用于处理文件格式可能没有任何对齐限制的网络或磁盘I/O的情况.

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.

这篇关于ArrayBufferView构造函数中的奇怪限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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