视图类型
ArrayBuffer, TypedArray, DataView
在剖析
在
const ab = new ArrayBuffer(32);
const iA = new Int8Array(ab);
iA[0] = 97; //把二进制的数据的首位改为97,97为小写字母a的 ascii 码;
const blob = new Blob([iA], { type: "application/octet-binary" }); //把二进制的码转化为blob类型
const url = URL.createObjectURL(blob);
window.open(url);
如果希望将
// ArrayBuffer -> Blob
const uint8Array = new Uint8Array([1, 2, 3]);
const arrayBuffer = uint8Array.buffer;
const blob = new Blob([arrayBuffer]);
// Blob -> ArrayBuffer
const uint8ArrayNew = null;
const arrayBufferNew = null;
const fileReader = new FileReader();
fileReader.onload = function (event) {
arrayBufferNew = event.target.result;
uint8ArrayNew = new Uint8Array(arrayBufferNew);
// warn if read values are not the same as the original values
// arrayEqual from: http://stackoverflow.com/questions/3115982/how-to-check-javascript-array-equals
function arrayEqual(a, b) {
return !(a < b || b < a);
}
if (arrayBufferNew.byteLength !== arrayBuffer.byteLength)
// should be 3
console.warn("ArrayBuffer byteLength does not match");
if (arrayEqual(uint8ArrayNew, uint8Array) !== true)
// should be [1,2,3]
console.warn("Uint8Array does not match");
};
fileReader.readAsArrayBuffer(blob);
fileReader.result; // also accessible this way once the blob has been read
TypedArray
// TypedArray
const typedArray = new Int8Array(10);
typedArray[0] = 8;
typedArray[1] = 127;
typedArray[2] = 128;
typedArray[3] = 256;
console.log("typedArray", " -- ", typedArray);
//Int8Array(10) [8, 127, -128, 0, 0, 0, 0, 0, 0, 0]
其他类型也都以此类推,可以存储的数据越长,所占的内存空间也就越大。这也要求在使用
DataView
// DataView
const arrayBuffer = new ArrayBuffer(8 * 10);
const dataView = new DataView(arrayBuffer);
dataView.setInt8(0, 2);
dataView.setFloat32(8, 65535);
// 从偏移位置开始获取不同数据
dataView.getInt8(0);
// 2
dataView.getFloat32(8);
// 65535
性能对比
// 普通数组
function arrayFunc() {
const length = 2e6;
const array = [];
const index = 0;
while (length--) {
array[index] = 10;
index++;
}
}
// dataView
function dataViewFunc() {
const length = 2e6;
const arrayBuffer = new ArrayBuffer(length);
const dataView = new DataView(arrayBuffer);
const index = 0;
while (length--) {
dataView.setInt8(index, 10);
index++;
}
}
// typedArray
function typedArrayFunc() {
const length = 2e6;
const typedArray = new Int8Array(length);
const index = 0;
while (length--) {
typedArray[index++] = 10;
}
}