Int32Array
A program needs millions of small integers in an array. With a typed array in Node.js, we can efficiently store these values.
For JavaScript, the typical array is a high-level type. An ArrayBuffer
and a "view" upon it like Int32Array
is a low-level array.
To use an efficient byte
array, we first create an ArrayBuffer
. We specify the exact number of bytes (not elements) we want in the constructor.
ArrayBuffer
. Here we use an Int32Array
to have 4-byte elements in our array.Int32Array
and read them back. In this way it is like any other array.// Create a buffer of 40 bytes. var buffer = new ArrayBuffer(4 * 10); // Use Int32Array on this buffer. var array = new Int32Array(buffer); // Assign elements. for (var i = 0; i < array.length; i++) { array[i] = i; } array[0] = 300; // Read from Int32Array. for (var i = 0; i < array.length; i++) { console.log("INT32ARRAY ELEMENT: " + array[i]); }INT32ARRAY ELEMENT: 300 INT32ARRAY ELEMENT: 1 INT32ARRAY ELEMENT: 2 INT32ARRAY ELEMENT: 3 INT32ARRAY ELEMENT: 4 INT32ARRAY ELEMENT: 5 INT32ARRAY ELEMENT: 6 INT32ARRAY ELEMENT: 7 INT32ARRAY ELEMENT: 8 INT32ARRAY ELEMENT: 9
A typed array can be initialized from an array literal. We pass the array directly to the Int32Array
constructor. Other constructors like Int8Array
also work.
Int32Array
around array literals. There is a conversion cost here.// Use array literal to create Int32Array. var values = new Int32Array([10, 8000000, 8]); for (var i = 0; i < values.length; i++) { console.log("INT32ARRAY ELEMENT: " + values[i]); } // Use array literal to create Int8Array. var valuesSmall = new Int8Array([0, 20, 1, 0]); for (var i = 0; i < valuesSmall.length; i++) { console.log("INT8ARRAY ELEMENT: " + valuesSmall[i]); }INT32ARRAY ELEMENT: 10 INT32ARRAY ELEMENT: 8000000 INT32ARRAY ELEMENT: 8 INT8ARRAY ELEMENT: 0 INT8ARRAY ELEMENT: 20 INT8ARRAY ELEMENT: 1 INT8ARRAY ELEMENT: 0
Suppose we want to manipulate 10 million integers. With an Int32Array
we save memory over an Array. I tested 2 programs with large arrays.
ArrayBuffer
has 40 million bytes, and the Array has 10 million objects.Int32
array program (1) uses about 7 MB less RAM when measured in Process Explorer on Windows.58.3 MB ArrayBuffer, Int32Array 65.3 MB Array
Many constructs in Node do not need low-level structures. But for an array with millions of elements, a typed array can make a program use much less memory.
With typed arrays, Node.js can support complex mathematical or numerical applications. Many numbers can be used in a program.