如何在Javascript中存储字节数组

时间:2022-04-14 15:41:36

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.

我将在Javascript中存储大量字节值(很可能超过100万)。如果我使用一个普通的带普通数字的数组,那将需要8 MB,因为数字存储为ieeedouble,但是如果我可以将它存储为字节,那么它将只有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.

显然,我不想浪费这么多空间。有办法将字节存储为字节而不是双字节吗?浏览器兼容性对我来说不是问题,只要它能在Chrome上运行。这是在HTML5中,如果有区别的话。

3 个解决方案

#1


45  

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

通过使用类型化数组,您可以存储这些类型的数组:

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

For example:

例如:

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

See it in action here.

在这里可以看到它的作用。

#2


5  

var array = new Uint8Array(100);    
array[10] = 256;
array[10] === 0 // true

I verified in firefox and chrome, its really an array of bytes :

我在firefox和chrome中验证过,它实际上是一个字节数组:

var array = new Uint8Array(1024*1024*50);  // allocates 50MBytes

#3


2  

You could store the data in an array of strings of some large fixed size. It should be efficient to access any particular character in that array of strings, and to treat that character as a byte.

您可以将数据存储在一些大的固定大小的字符串数组中。访问字符串数组中的任何特定字符并将该字符视为字节应该是有效的。

It would be interesting to see the operations you want to support, perhaps expressed as an interface, to make the question more concrete.

看到您希望支持的操作(可能表示为接口)使问题更具体,这将是很有趣的。

#1


45  

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

通过使用类型化数组,您可以存储这些类型的数组:

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

For example:

例如:

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

See it in action here.

在这里可以看到它的作用。

#2


5  

var array = new Uint8Array(100);    
array[10] = 256;
array[10] === 0 // true

I verified in firefox and chrome, its really an array of bytes :

我在firefox和chrome中验证过,它实际上是一个字节数组:

var array = new Uint8Array(1024*1024*50);  // allocates 50MBytes

#3


2  

You could store the data in an array of strings of some large fixed size. It should be efficient to access any particular character in that array of strings, and to treat that character as a byte.

您可以将数据存储在一些大的固定大小的字符串数组中。访问字符串数组中的任何特定字符并将该字符视为字节应该是有效的。

It would be interesting to see the operations you want to support, perhaps expressed as an interface, to make the question more concrete.

看到您希望支持的操作(可能表示为接口)使问题更具体,这将是很有趣的。