5

I've found many ways to create a Float32Array from an array, but all of them involve copying all elements. I want to avoid that cost, because the array will never be used again. I just want to cast it. How is that possible?

MaiaVictor
  • 51,090
  • 44
  • 144
  • 286
  • Check this answer and flip the implementation around? http://stackoverflow.com/questions/12760643/how-to-convert-javascript-float32array-into-javascript-array – Kyle Pittman Jun 06 '14 at 00:43
  • No, this answer involves making a whole new copy of the array. – MaiaVictor Jun 06 '14 at 00:48
  • I don't think you can just "cast" it as they are likely different data structures since a normal array can contain any type of element, not just numbers so JS has to include some type info in a normal array element. The info in the answer Kyle references just uses `.slice()` to do a copy. – jfriend00 Jun 06 '14 at 01:00
  • 2
    This is a *conversion* operation; as such the result (in either direction) is a new array/object, even if the loop is hidden by some function. Unlike a per-item conversion (e.g. Array of number -> Array of string), a Float32Array object is represented by a specialized implementation and separate from any standard Array/object, which is why the entire array itself must be "new". – user2864740 Jun 06 '14 at 01:05

1 Answers1

12

It's impossible. A Float32Array is always a different object than a normal array.

If you want to avoid the cost of copying the items, a) don't use a normal array in the first place or b) let your function that uses it work with normal arrays as well.

If you are looking for the "casting" operation, you can just invoke the Float32Array constructor with the normal array:

var arr = [0.3, 1, 2];
var typedArr = new Float32Array(arr);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375