MENU
Typed Arrays
JavaScript arrays can grow and shrink dynamically and can have any JavaScript value. This flexibility comes at a performance cost. Many web applications, such as those manipulating WebGL, WebSockets, audio, and video, prefer access to raw fixed-length binary data. This results in the introduction of typed arrays into JavaScript.
There are several ways to initialize a TypedArray:new TypedArray(); // new in ES2017
new TypedArray(length);
new TypedArray(typedArray);
new TypedArray(object);
new TypedArray(buffer [, byteOffset [, length]]);Typed arrays are implemented using viewsviews views : Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array. Uint8ClampedArray clamps the values between 0 and 255.
Typed Arrays share almost all properties and methods of Array. The unsupported methods include:
Array.isArray()
Array.prototype.concat()
Array.prototype.push()
Array.prototype.pop()
Array.prototype.unshift()
Array.prototype.shift()
Also, typed arrays have the following properties/methods:
.BYTES_PER_ELEMENT .name .prototype.buffer .prototype.byteLength
.prototype.byteOffset
.prototype.length
.prototype.set()
.prototype.subarray()
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var a = Int8Array.from([1,2,3]);
console.log(a.BYTES_PER_ELEMENT); // 1
console.log(Int8Array.name); // Int8Array
console.log(a.buffer); // ArrayBuffer {}
console.log(a.byteLength); // 3
console.log(a.byteOffset); // 0
console.log(Array.isArray(a)); // false
a[1] = 3;
console.log(a); // [1,3,3]
a.set([4,5],1);
console.log(a); // [1,4,5] //a.set(a,1); // RangeError: Source is too large
var b = a.subarray(1,3);
console.log(b); // [4,5] // b.concat(a); // TypeError
[...c] = [...b];
console.log(c); // [4,5]
console.log(Array.isArray(c)); // true
</script></body><html>
This demonstrates the performance benefit of using a typed array.
RESETRUNFULL
<!DOCTYPE html><html><body><script>
var a = new Array(1024);
var ta = Float64Array.from(a);
var t1 = Date.now();
for (i=0; i<100000; i++) a.copyWithin(0);
var t2 = Date.now();
for (i=0; i<100000; i++) ta.copyWithin(0);
var t3 = Date.now();
console.log(t2-t1); // 3987
console.log(t3-t2); // 12
</script></body><html>