In typed array specification there is a constructor that allows to take an existing ArrayBuffer and treat is as another array type. It is interesting that offset parameter must be a multiple of the underlying type of the constructed array. What was the reason for this limitation?
For background - I am trying to encode a binary buffer to be sent over WebSocket. The buffer contains various variables of different size. Originally I wanted to use the following code:
var buffer = new ArrayBuffer(10);
new Uint32Array(buffer, 0, 1)[0] = 234;
new Int16Array(buffer, 4, 1)[0] = -23;
new Uint32Array(buffer, 6, 1)[0] = 6000; // Exception is raised here,
// because 6 is not multiple of 4
To make this work I would need to rewrite last line as following:
var tempArray = new Uint32Array(1); // Create 32-bit array
tempArray[0] = 6000; // Write 32-bit number
var u8Src = new Uint8Array(tempArray, 0); // Create 8-bit view of the array
var u8Dest = new Uint8Array(buffer, 6, 4); // Create 8-bit view of the buffer
u8Dest.set(u8Src); // Copy bytes one by one
This is too much code for such a simple operation.
A typed array significantly simplifies the level of proof the engine needs to be able to optimise around it. A value returned from a typed array is certainly of a certain type, and engines can optimise for the result being that type.
A TypedArray object describes an array-like view of an underlying binary data buffer. There is no global property named TypedArray , nor is there a directly visible TypedArray constructor.
JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast.
The Uint8Array() constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to 0 . Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).
Unaligned memory access doesn't work on all platforms:
Why is creating a Float32Array with an offset that isn't a multiple of the element size not allowed? http://en.wikipedia.org/wiki/Data_structure_alignment
Use DataView object to access non-aligned data:
https://developer.mozilla.org/en-US/docs/JavaScript/Typed_arrays/DataView
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With