📜 ⬆️ ⬇️

Typed Arrays

With the advent of WebGL, several new data types have emerged, in particular, typed arrays. They all have a similar interface and are much faster than regular arrays, have border control and only two methods and one property. At the moment, if I'm not mistaken, then the typed arrays are supported by the latest versions of FireFox and Chrome.
More information about typed arrays can be found in the specification.
Well, in the article we will look at the basics of the basics.

Types of typed arrays


Table stolen from specification

Type ofSize in bytesDescriptionAnalog in C
Int8Arrayone8-bit signed integersigned char
Uint8Arrayone8-bit without signed integerunsigned char
Int16Array216-bit signed integershort
Uint16Array216-bit without signed integerunsigned short
Int32Arrayfour32-bit signed integerint
Uint32Arrayfour32-bit without signed integerunsigned int
Float32Arrayfour32-bit floating point numberfloat
Float64Arrayeight64-bit floating point numberdouble



Create a typed array


To create a typed array, you need to use a constructor whose name is similar to the type name, for example, consider Uint8Array.
 var ls1 = new Uint8Array(10), //      ls2 = new Uint8Array([1,2,3,4,5]); //     (  imageData    ),          


Fill the array


Index filling works in the same way as in any other arrays, but in addition to them, you can insert another array with the specified offset into the array.
 ls1.set(ls2,3); //   -            undefined,  0. 

')

Get the sub-array


In addition, we can get part of the array.
 var ls3 = ls1.subarray(2,5), //{0:0, 1:1, 2:2, 3:3, 4:4} -- -    2-  5- ls4 = ls1.subarray(6); //{0:4, 1:5, 2:0, 3:0} -- -    6-   


Performance


Consider a simple synthetic test designed specifically for quick work with typed values.
Option using typed arrays.
 var ls1 = new Uint8Array(320000), ls2 = new Uint8Array(320000), ls3 = new Uint8Array(320000); for(var i=0;i<319999;i++){ ls1[i] = i; ls2[i] = 32-i; } //4ms for(var i=0;i<319999;i++){ ls3[i] = ls1[i] * ls2[i]; }//15ms ls1.set(ls3.subarray(30,60),30) //11ms 


 var ls1 = [], ls2 = [], ls3 = []; for(var i=0;i<319999;i++){ ls1[i] = i; ls2[i] = 32-i; } //26ms for(var i=0;i<319999;i++){ ls3[i] = ls1[i] * ls2[i]; } //19ms ls1.splice(30,30,ls3.slice(30,60)) //7ms 

As you can see, typed arrays are not yet very fast in terms of the functions of arrays, but otherwise they outperform ordinary arrays in performance.

Update: transfer of the wrong type


As suggested in the comments . WebGL uses type conversion rules from ECMA-262 (point 3 - Type Conversion Rules in the WebGL spec).
 a = new Uint8Array(3); a[1] = 4; a[1] = 'asdasdsad'; a == {0:0, 1:0, 2:0} 

Source: https://habr.com/ru/post/119694/


All Articles