我一直在寻找如何调整ArrayBuffers大小的方法,下面是两种方法:
1(Uint8Array):
function resizeUint8(baseArrayBuffer, newByteSize) {
var resizedArrayBuffer = new ArrayBuffer(newByteSize),
resizedView = new Uint8Array(resizedArrayBuffer),
baseView = new Uint8Array(baseArrayBuffer);
for(var i = 0; i < baseView.length; i++) {
resizedView[i] = baseView[i];
}
return resizedArrayBuffer;
}
2(Float64Array):
// newByteSize is divisible by 8
function resizeFloat64(baseArrayBuffer, newByteSize) {
var resizedArrayBuffer = new ArrayBuffer(newByteSize),
resizedView = new Float64Array(resizedArrayBuffer),
baseView = new Float64Array(baseArrayBuffer);
for(var i = 0; i < baseView.length; i++) {
resizedView[i] = baseView[i];
}
return resizedArrayBuffer;
}
比较:#1利用Uint8Arrays,因此对于baseArrayBuffer中的每个字节,您必须将其分别复制到调整大小的数组缓冲区中.现在,对于#2,我使用了Float64Array,因此我可以迭代减少8倍以上的索引来获得相同的结果.
关注:使用Float64Array似乎是显而易见的“性能更高”的方法.但是,使用Float64Array时我缺少什么吗?通过Float64Array视图设置每个索引时,我是否会失去数值精度?还有其他缺点吗(除了确保字节大小可以被8整除)?
解决方法:
不用复制for循环中的每个元素,而是使用typedArray.set方法,它更快
function resizeUint8(baseArrayBuffer, newByteSize) {
var resizedArrayBuffer = new ArrayBuffer(newByteSize),
len = baseArrayBuffer.byteLength,
resizeLen = (len > newByteSize)? newByteSize : len;
(new Uint8Array(resizedArrayBuffer, 0, resizeLen)).set(new Uint8Array(baseArrayBuffer, 0, resizeLen));
return resizedArrayBuffer;
}
JSFiddle测试:http://jsfiddle.net/92zsn529/