I am wanting to compress results from QUERYS of the database before adding them to the cache.
I want to be able to compress any reference type.
I have a working version of this for compressing strings.. the idea based on scott hanselman 's blog post http://shrinkster.com/173t
any ideas for compressing a .net object?
I know that it will be a read only cache since the objects in the cache will just be byte arrays..
This won't work for any reference type. This will work for Serializable types. Hook up a
BinaryFormatter
to a compression stream which is piped to a file:You could use a
MemoryStream
to hold the contents in memory, rather than writing to a file. I doubt this is really an effective solution for a cache, however.I just added GZipStream support for my app today, so I can share some code here;
Serialization:
Deserialization:
NOTE: if you use CryptoStream, it is kinda important that you chain (un)zipping and (de)crypting right this way, because you'll want to lose your entropy BEFORE encryption creates noise from your data.
What sort of objects are you putting in the cache? Are they typed objects? Or things like
DataTable
? ForDataTable
, then perhaps store as xml compressed throughGZipStream
. For typed (entity) objects, you'll probably need to serialize them.You could use
BinaryFormatter
andGZipStream
, or you could just use something like protobuf-net serialization (free) which is already very compact (addingGZipStream
typically makes the data larger - which is typical of dense binary). In particular, the advantage of things like protobuf-net is that you get the reduced size without having to pay the CPU cost of unzipping it during deserialization. In some tests before addingGZipStream
, it was 4 times faster thanBinaryFormatter
. Add the extra time ontoBinaryFormatter
for GZip and it should win by a considerable margin.Here is how this can be done.
GzipStream: Provides methods and properties used to compress and decompress streams.
Serialize object to Memory stream using binaryformatter and hook that memorystream to Gzipstream.
Code to compress is as follows: