web-audio-samples icon indicating copy to clipboard operation
web-audio-samples copied to clipboard

Float32Array.subarray() may allocate memory

Open chrisguttandin opened this issue 9 months ago • 1 comments

I noticed that the FreeQueueSAB class uses Float32Array.subarray() when copying data from or to the SharedArrayBuffer. According to the EcmaScript spec (at least as far as I understand it) this should create a new Float32Array instance.

Interestingly when I profile the following snippet in Chrome I only see two newly created Float32Array instances.

const source = new Float32Array(100000);
const target = new Float32Array(100000);

for (let i = 0; i < 100000; i += 1) {
  target.set(source.subarray(i, 100000), i);
}

Is that a known optimization that the temporary Float32Array will not actually be created in this case when it is only used to determine the range for the following call to set()? Is it save to count on that? I used the allocation timeline in DevTools to get the number of instances. Maybe it's not capable of tracking very short lived objects.

Firefox seems to be doing something similar allthough it creates three Float32Array instances when running the example above.

I also profiled the following snippet as a sanity check. It creates 100001 Float32Array instances in Chrome as expected. Similar to the other snippet it also creates one more instance (100002) in Firefox.

const source = new Float32Array(100000);
const subarrays = [];

for (let i = 0; i < 100000; i += 1) {
  subarrays.push(source.subarray(i, 100000));
}

chrisguttandin avatar Apr 17 '25 01:04 chrisguttandin

That's very interesting. I was not aware of this difference between browsers.

this should create a new Float32Array instance.

This is definitely not what we wanted, but I guess it fell through the code review. But also, MDN says "note that this is creating a new view on the existing buffer; changes to the new object's contents will impact the original object and vice versa."

So the returned subarray has the same backing buffer, so at least it doesn't clone the entire data.

If you have a suggestion to optimize this, I'd love to know!

hoch avatar Apr 24 '25 16:04 hoch

@chrisguttandin please have a look i have made the pr

Aditya30ag avatar Jul 09 '25 17:07 Aditya30ag

Fixed by #424

mjwilson-google avatar Sep 04 '25 18:09 mjwilson-google