Is the conversion of an Array into Float32Array rather than just making a Float32Array to start intentional?

I notice that in the examples, it is common to make an array of numbers for position/normals/UV and then convert this into a Float32Array.

I have read that in general Float32Array is slower in some ways but necessary for the system to work with. This approach means copying all the data once at least though.

I presume this is just for readability or so you don’t have to instantiate the size? The example there seems actually more confusing in my opinion because they keep copying the data around.

If you know the size of the Float32Array (as you should in these examples) is there any reason not to go:

position = new Float32Array(numEntries);
for (let i=0; i<position.length;i++){
position[i] = value;
}

And then you don’t have to copy the data over? Or is copying all the data so the conversion happens all at once somehow optimized that it is favorable?

I am not used to Javascript and these quirks. For example in C++/C# it is common sense that you should always define the size of your arrays/lists/etc on creation so as not to “push” even when it is possible as “pushing” can result in the objects all being copied again in memory. But I read in Javascript this is not an issue? Interesting if so.

Thanks for any thoughts.

I suspect it’s a mix of readability, web developer habit, and just old code. In web development applications outside of graphics, typed arrays are less common, and their benefits more limited. three.js began around 2010, and typed arrays didn’t even enter the language until ECMAScript 2015.

But you’re right – if you know the size of a large array, it’s better to pre-allocate the typed array up front, and that’s what we should be aiming for in most examples moving forward.

2 Likes