Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Javascript typed arrays initialized to 0?

I need a typed array, specifically a Float32Array, of all zeros. I was thinking that I would have to clear it manually, but I noticed that when I declared it, it was already zeroed out. Is this something that is specified in the spec? Can I rely on this behavior?

like image 845
SharkCop Avatar asked Aug 17 '12 17:08

SharkCop


People also ask

What is a typed array in JavaScript?

JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast.

Why might you use typed arrays instead of standard arrays?

Normal arrays can be as fast as typed arrays if you do a lot of sequential access. Random access outside the bounds of the array causes the array to grow. Typed arrays are fast for access, but slow to be allocated. If you create temporary arrays frequently, avoid typed arrays.

What is a zero filled array?

Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.

What is JavaScript ArrayBuffer?

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".


1 Answers

According to JavaScript's Typed Array Specification, contents are initialized to 0. So you should be able to rely on this behavior.

Be aware that typed arrays don't have very good cross browser support yet. Chrome, Safari, Firefox, and Opera support it, but Internet Explorer only introduced support in IE10.

I should also mention that typed arrays are currently extremely slow in Safari compared to normal arrays. For this reason, you're probably better off avoiding typed arrays unless you aren't targeting Safari. Using normal arrays, all array values are initialized as undefined.

like image 61
Dan Herbert Avatar answered Oct 15 '22 04:10

Dan Herbert