I was doing some code review and have come across the below code
private static string ZipStream(string sxml)
{
byte[] binaryData;
var bytes = Encoding.UTF8.GetBytes(sxml);
int x = sxml.Length;
using (var msi = new MemoryStream(bytes))
{
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
byte[] bytes2 = new byte[600000];
int count;
while ((count = msi.Read(bytes2, 0, bytes.Length + 1000)) != 0)
{
gs.Write(bytes2, 0, count);
}
}
binaryData = mso.ToArray();
return Convert.ToBase64String(binaryData);
}
}
}
I found it difficult to understand the above code in one reading and also found that if the input string is more than 600000 bytes the above code will throw error. So i updated it to below code. When i ran both pieces of code in a console ap in a loop for 10000 times on a string of length 20 chars, the first version takes 2.4MB of memory and second one(my updated code) takes 6.5MB of memory. For the life of me I can't seem to understand why is this happening?
private static string ZipStreamUpdated(string sxml)
{
var bytes = Encoding.UTF8.GetBytes(sxml);
using (var mso = new MemoryStream(bytes.Length))
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
gs.Write(bytes, 0, bytes.Length);
}
return Convert.ToBase64String(mso.ToArray());
}
}