I have two cases on using node js Buffer in different place:
- Buffer accumulation, which I have several buffers and will combine all of them together in the end.
- Buffer writer, which I just need to resize the Buffer when it's insufficient anymore to hold more data.
Naturally, I will use Buffer.concat for the first case and Buffer.copy for
the second case. But, that can be reversed in which I can use Buffer.copy for
the first case and Buffer.concat for the second case.
Implementation 1 Buffer.concat for first case and Buffer.copy for second case:
// first case: buffer accumulation
const result = Buffer.concat([arrayOfBuffers])
// second case: buffer writer
if (oldbuffer.length - offset < newdata.length) {
const newsize = oldbuffer.length * growthFactor + newdata.length
const newbuffer = Buffer.alloc(newsize)
oldbuffer.copy(newbuffer)
newdata.copy(newbuffer, offset)
result = newbuffer
}
// newbuffer is the end result
Implementation 2 Buffer.copy for second case and Buffer.concat for first case:
// first case: buffer accumulation
const totalSize = arrayOfBuffers.reduce((size, buff) => size + buff.length, 0)
const result = Buffer.alloc(totalSize)
let offset = 0
for (const buff of arrayOfBuffers) {
buff.copy(result, offset)
offset += buff.length
}
// second case: buffer writer
const result = Buffer.concat([oldbuffer, newdata])
I don't know how both concat and copy internally works in node js. So,
which method is best for both case?