GZipStream
and DeflateStream
don’t buffer their input, so they will only compress the individual chunks
that are passed to Write
(or, worst-case, WriteByte
). Unless you can
guarantee that large blocks of data are being passed to GZipStream.Write
,
always wrap GZipStream
in a BufferedStream
when using CompressionMode.Compress
.
In fact, if you call only WriteByte
on a compressing GZipStream
, it will
create “compressed” output that’s almost double the size of
the input.
Experimentation determined that the optimal buffer size is 8K; above
this, no further compression is gained. So, to create a GZipStream
, use
a method similar to the following:
This chart shows how the compressed output keeps getting smaller as the buffer size increases (and how writing just one or two bytes at a time almost doubles the 1MB input):
Posted by Bradley Grainger on June 08, 2012