How to store a byte array in Javascript

Kendall Frey picture Kendall Frey · Sep 8, 2012 · Viewed 98.3k times · Source

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.

Answer

Kendall Frey picture Kendall Frey · Sep 8, 2012

By using typed arrays, you can store arrays of these types:

  • Int8
  • Uint8
  • Int16
  • Uint16
  • Int32
  • Uint32
  • Float32
  • Float64

For example:

​var array = new Uint8Array(100);
array[42] = 10;
alert(array[42]);​

See it in action here.