如何在 Javascript 中存储字节数组 [英] How to store a byte array in Javascript
问题描述
我将在 Javascript 中存储大量字节值(很可能超过一百万).如果我使用带有普通数字的普通数组,则需要 8 MB,因为数字以 IEEE 双精度形式存储,但如果我可以将其存储为字节,则只有 1 MB.
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.
出于显而易见的原因,我想避免浪费那么多空间.有没有办法将字节存储为字节而不是双精度?浏览器兼容性对我来说不是问题,只要它在 Chrome 中工作即可.这是在 HTML5 中,如果这有区别的话.
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:
类型 | 值范围 | 大小(字节) |
---|---|---|
Int8Array | -128 到 127 | 1 |
Uint8Array | 0 到 255 | 1 |
Uint8ClampedArray | 0 到 255 | 1 |
Int16Array | -32768 到 32767 | 2 |
Uint16Array | 0 到 65535 | 2 |
Int32Array | -2147483648 到 2147483647 | 4 |
Uint32Array | 0 到 4294967295 | 4 |
Float32Array | -3.4E38 到 3.4E38 | 4 |
Float64Array | -1.8E308 到 1.8E308 | 8 |
BigInt64Array | -2^63 到 2^63 - 1 | 8 |
BigUint64Array | 0 到 2^64 - 1 | 8 |
Stack Snippets 中的演示 &JSFiddle
var array = new Uint8Array(100);
array[42] = 10;
console.log(array[42]);
这篇关于如何在 Javascript 中存储字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!