public static byte[] Compress(byte[] data)
{
using (MemoryStream ms = new MemoryStream())
{
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress))
{
ds.Write(data, 0, data.Length);
ds.Flush();
}
return ms.ToArray();
}
}
Will the memorystream be closed in the function above?
Or is it better to assign the memorystream to an array and return the array instead?
public static byte[] Compress(byte[] data)
{
byte[] compressedData;
using (MemoryStream ms = new MemoryStream())
{
using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress))
{
ds.Write(data, 0, data.Length);
ds.Flush();
}
compressedData= ms.ToArray();
}
return compressedData;
}
Which of the codes better optimize memory usage?
Very similar results and not worth the effort.
To Answer your question the memory stream gets closed because it leaves scope and is in a using block meaning Dispose will get called ala the IDispose pattern. As an aside I personally prefer your second example as its easier to stop it in the debugger to check the contents of
compressedData. But this really isn’t worth the effort to refactor in the name of performance.There are bigger gains to be had elsewhere.
Example code here from
MemoryStream.toArraylooks like thisthe reason the stream will be closed is because it is not held onto by your code at all and all references are dropped as the contents of the stream was copied to an array.
Inside memory stream is this code