How to store a byte array in Javascript
I'm going to be storing a large array of byte values (most likely over a million) in Javascript. If I use a normal array with normal numbers, that will take 8 MB, because numbers are stored as IEEE doubles, but if I can store it as bytes, it will be only 1 MB.
I'd like to avoid wasting that much space for obvious reasons. Is there a way to store bytes as bytes instead of doubles? Browser compatibility isn't an issue for me, as long as it works in Chrome. This is in HTML5, if that makes a difference.
By using typed arrays, you can store arrays of these types:
Type | Value Range | Size(bytes) |
---|---|---|
Int8Array |
-128 to 127 | 1 |
Uint8Array |
0 to 255 | 1 |
Uint8ClampedArray |
0 to 255 | 1 |
Int16Array |
-32768 to 32767 | 2 |
Uint16Array |
0 to 65535 | 2 |
Int32Array |
-2147483648 to 2147483647 | 4 |
Uint32Array |
0 to 4294967295 | 4 |
Float32Array |
-3.4E38 to 3.4E38 | 4 |
Float64Array |
-1.8E308 to 1.8E308 | 8 |
BigInt64Array |
-2^63 to 2^63 - 1 | 8 |
BigUint64Array |
0 to 2^64 - 1 | 8 |
Demo in Stack Snippets & JSFiddle
var array = new Uint8Array(100);
array[42] = 10;
console.log(array[42]);
var array = new Uint8Array(100);
array[10] = 256;
array[10] === 0 // true
I verified in firefox and chrome, its really an array of bytes :
var array = new Uint8Array(1024*1024*50); // allocates 50MBytes