What is Typedarray? What are the advantages of using them compared to the traditional Array?

Asked

Viewed 118 times

11

I was reading on MDN about Typedarray and saw that various classes derive from this.

Classes derived from TypeArray:

  • Int8array
  • Uint8array
  • Uint8clampedarray
  • Int16array
  • Uint16array
  • Int32array
  • Uint32array
  • Float32array
  • Float64array

From what I understand, each of these "arrays" accept a different type of input.

A test with Int8Array:

var arr = new Int8Array(4);

arr[0] = 1;
arr[1] = 2;
arr[2] = 2.5; 
arr[3] = "X2.5"; 


console.log(arr, arr.constructor.name);

In the above case, 2.5 as the value string, were converted to int.

Bearing in mind that these arrays have this kind of behavior, I’d like to ask some questions:

  • In which cases should I use the TypedArray instead of Array Javascript standard? Would you like examples

  • Is there any performance gain when using a TypedArray instead of using the Array?

  • I would like to know about compatibility and polyfills on the same.

  • 2

    Another difference is initialization. Comparing for example new Int8Array(4) to new Array(4) where in the latter the elements are all as undefined. Just as they also define the size of each element of the array in bytes

  • Thanks for the remark, @Isac.

1 answer

8


In which cases should I use Typedarray instead of the standard Javascript array? Would you like examples

To MDN documentation gives 3 examples: the Apis of FileReader, of XMLHttpRequest and of ImageData. And I remember a fourth that I’ve posted here on Get "waves" from sound or music frequency, connected to a component of the audio Apis.

There is some performance gain when using Typedarray instead of using Array?

Yes. Basically these arrays work by allocating a block of memory to the data and mapping this block according to the types. Since each type has a fixed size, it is possible to obtain the value of any index of the array in constant time. Common JS arrays are not typed, and finding values in them is less efficient by nature.

I would like to know about the compatibility and polyfills on them.

The support is very broad, goes up to IE 10, early versions of FF and Chrome, and Safari 5.1. It also has good mobile support. See the first link of this reply, at the end of the article has a compatibility table.

About polyfills, I don’t think they make much sense in this case. If the goal of typed arrays is to gain performance, building a polyfill for this feature would only mean losing more performance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.