Is there a way to compress an object in memory and use it transparently?
It really depends on the type of that you're working with. One possibility is to compress your objects, keeping them as a compressed byte[]
instead of raw object format using an Extension Method.
You could combine that along with making your process work x64 bit:
public static byte[] SerializeAndCompress(this object obj)
{
using (MemoryStream ms = new MemoryStream())
using (GZipStream zs = new GZipStream(ms, CompressionMode.Compress, true))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(zs, obj);
return ms.ToArray();
}
}
public static T DecompressAndDeserialize<T>(this byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
using (GZipStream zs = new GZipStream(ms, CompressionMode.Decompress, true))
{
BinaryFormatter bf = new BinaryFormatter();
return (T)bf.Deserialize(zs);
}
}
Code of "Yuval Itzchakov" has an error!; he execute ms.ToArray();
before close the compressor.
This will cause error in DecompressAndDeserialize method.
this code will work:
public static byte[] SerializeAndCompress(this object obj)
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream zs = new GZipStream(ms, CompressionMode.Compress, true))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(zs, obj);
}
return ms.ToArray();
}
}: