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, eve开发者_运维百科n 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?
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.
精彩评论