What is the fastest way to copy one ArrayBuffer object to another? In particular, it is necessary from time to time to increase the buffer size by a certain length, which is achieved by creating a new ArrayBuffer greater length and copying the contents of the previous ArrayBuffer .
1 answer
There are two ways to extend an ArrayBuffer object.
1) Copy data manually via DataView .
var ob = new ArrayBuffer(1024); var nb = new ArrayBuffer(2048); var nv = new DataView(nb); var ov = new DataView(ob); for (var i = 0; i < 1024; i += 8) { nv.setFloat64(i, ov.getFloat64(i)); } And it is worth noting that this will be most effective if you copy 8 bytes over getFloat64() (the gain is about 8 times as compared with byte-by-copy copying via getUint8() ).
2) Use typed arrays created on the basis of ArrayBuffer .
var ob = new ArrayBuffer(1024); // старый буфер var nb = new ArrayBuffer(2048); // новый буфер new Uint8Array(nb).set(new Uint8Array(ob)); // копируем через массивы Testing both methods when copying an array of 16 MB in size ( new ArrayBuffer(16777216) ) into an array twice as long, gave the following results: the first method took 456 milliseconds, and the second approximately 11 milliseconds.
Obviously, the second method is incomparably better.
It is worth noting that in the Mozilla browser there is ArrayBuffer.transfer() for the purpose of expanding ArrayBuffer , however this is still an experimental technology.
The idea of expanding ArrayBuffer through typed arrays is taken from here.