I saw a lot of examples of CopyStream implementation but I have question about buffer size when we copy streams.
Sample of one of CopyStreams implementation:
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
Questions are:
- What buffers Length should be (I've seen 256, 8 * 1024, 32768)?
- How different buffer size affects performance, memory usage etc.?
Related questions:
File IO with Streams - Best Memory Buffer Size - nice File IO answer. But what about in memory copying?
My case:
There is MemotyStream
which I create using ClosedXML workbook.SaveAs(memoryStream);
and it allocates huge amount of memory in managed heap. I've looked into sources and found that there is CopyStream method that uses 8 * 1024 buffer size. Could changing this size somehow decrease memory usage?
Note: Stream takes almost 1Gb of memory.