Does BinaryFormatter use any compression?

When the .NET BinaryFormatter used to serialize a graph of objects, does any type of compression apply?

I ask in the context of whether I should worry about a graph of objects that has many duplicate rows and integers.

Change Hold on, if strings are interned in .NET, you don't have to worry about duplicate strings, right?

+7
c # serialization compression binaryformatter
source share
2 answers

No, it does not provide any compression, but you can compress the output yourself using GZipStream .

Edit: Mehrdad has a great example of this technique in his answer to How to compress an .net object instance using gzip .

Edit 2: Rows can be interned, but that does not mean that every row is interned. I would not make any assumptions about how and why the CLR resolves static strings, as this can change (and has changed) from version to version.

+10
source share

No, it’s not, but ...

I just added GZipStream support for my application today, so I can share some code here;

Serialization:

 using (Stream s = File.Create(PathName)) { RijndaelManaged rm = new RijndaelManaged(); rm.Key = CryptoKey; rm.IV = CryptoIV; using (CryptoStream cs = new CryptoStream(s, rm.CreateEncryptor(), CryptoStreamMode.Write)) { using (GZipStream gs = new GZipStream(cs, CompressionMode.Compress)) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(gs, _instance); } } } 

Deserialization:

 using (Stream s = File.OpenRead(PathName)) { RijndaelManaged rm = new RijndaelManaged(); rm.Key = CryptoKey; rm.IV = CryptoIV; using (CryptoStream cs = new CryptoStream(s, rm.CreateDecryptor(), CryptoStreamMode.Read)) { using (GZipStream gs = new GZipStream(cs, CompressionMode.Decompress)) { BinaryFormatter bf = new BinaryFormatter(); _instance = (Storage)bf.Deserialize(gs); } } } 

NOTE. If you use CryptoStream, it is important that you chain (un) zipping and (de) encrypt this way because you want to lose your entropy BEFORE encryption creates noise from your data.

+4
source share

All Articles