3

Is there a method to set all indices in an ArrayBuffer to 0 that is optimized to be fast? I know I can do an iteration to do it manually but I was wondering if there is some built-in that does it fast as I want to do this once per animation frame.

Alex Bollbach
  • 4,370
  • 9
  • 32
  • 80

1 Answers1

5

There is no reason to initialize the memory in an ArrayBuffer to 0, because this is automatically done when the array is created:

From MDN:

Return value

A new ArrayBuffer object of the specified size. Its contents are initialized to 0.

This default dates back all the way to the obsolete initial spec, and all browsers should behave this way.

Besides, it stands to reason the memory would be cleared on allocation, else who knows what memory an attacker might be able to access.

For all other purposes:

If you need to initialize it to a value other than 0 or clear out existing data, you can use the native fill method which you can use on a typed array view (like Uint8Array) of the ArrayBuffer. Browser supports is not so great though, so you may want to load up a polyfill for old browsers.

Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
  • actually fill was in the back of my brain and i used it recently to initialize a chunk of data to 0. I wonder, how the act of requesting new new chunk of say, 1000000 bytes for an arraybuffer compares to initializing it to 0 in terms of operational runtime. – Alex Bollbach Aug 27 '16 at 05:55