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

10

I was reading in MDN about TypedArray and saw that several classes derive from this.

Classes that are derived from TypeArray :

  • Int8Array
  • Uint8Array
  • Uint8ClampedArray
  • Int16Array
  • Uint16Array
  • Int32Array
  • Uint32Array
  • Float32Array
  • Float64Array

As I understand it, 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 .

Given that these arrays have this type of behavior, I would like to ask some questions:

  • In what cases should I use TypedArray instead of% default Array of Javascript? I would like examples

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

  • I'd like to know about the compatibility and polyfills about the same.

asked by anonymous 17.08.2018 / 16:30

1 answer

7
  

In what cases should I use TypedArray instead of the default Javascript Array? I would like examples

The MDN documentation gives 3 examples: FileReader , from XMLHttpRequest and do ImageData . And I remember a 4th I already posted here on the site in , linked to a

org / en-US / docs / Web / API / AnalyserNode "> audio APIs component .

  

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

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

  

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

Support is quite broad, going up to IE 10, early versions of FF and Chrome, and Safari 5.1. Also has good support in mobile. See the first link of this answer, at the end of the article has a compatibility chart.

On polyfills, I do not think they make much sense in this case. If the purpose of typed arrays is to gain performance, building a polyfill for this feature would only mean losing even more performance.

    
17.08.2018 / 19:48