Strange limitation in ArrayBufferView constructor [duplicate]

旧街凉风 提交于 2019-12-01 07:17:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7554462/strange-limitation-in-arraybufferview-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!