I can't use .push() on a Float32Array, I get an error, so I tried to add it like this :
myarray = new Float32Array() ;
myarray.push = function()
{
for( var i in arguments )
{
this[this.length] = arguments[i] ;
}
} ;
But it does not work. I do not get errors, but my array's values are all 0. Why ?
The Float32Array typed array represents an array of 32-bit floating point numbers (corresponding to the C float data type) in the platform byte order. If control over byte order is needed, use DataView instead. The contents are initialized to 0 .
The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".
The JavaScript TypedArray object illustrates an array like view of an underlying binary data buffer. There are many number of different global properties, whose values are TypedArray constructors for specific element types, listed below.
Basically a Float32Array
is just a view over an ArrayBuffer
object (as are all typed arrays in JS). This ArrayBuffer
has a fixed length, which in turn the Float32Array
inherits.
So to conclude: You just can not change the size of your Float32Array
on the fly. The only possibility would be as this:
If you want to add multiple values on multiple occasions, I strongly advise against this. This completely negates any performance advantage you might gain from using typed arrays!
Typed arrays like Float32Array is designed as lower level approach which make more sense if you are familiar with dynamic memory allocation (like in C).
Here we have memory allocated (the underlying ArrayBuffer) and memory used (assigned items in typed array), which doesn't have to be the same thing in raw memory.
You can push to typed arrays like this:
(myarray = new Float32Array(myarray.length+1)).set([...myarray, appendix])
where appendix
is the new item you want to push. It is not just ugly, but also very ineffective: you should predict how much the array would grow and allocate more extra space instead of just +1
(and remember how much space is left).
To make it memory effective, you could share one underlying ArrayBuffer (see examples here), just remember that every item in Float32Array takes 4 bytes in ArrayBuffer.
If you dont want to bother with this and you just want to push anytime, just stay with the old generic Array.
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