1

Possible Duplicate:
Fastest serializer and deserializer with lowest memory footprint in C#?

I'm using BinaryFormatter class to serialize an structure or a class. (after serialization, I'm going to encrypt the serialized file before saving. (And of course decrypt it before deserialization))

But I heard that some other serialization classes are present in .Net Framework. Like XmlSerializer, JavaScriptSerializer, DataContractSerializer and protobuf-net.

I want to know, which one is best for me?

Less RAM space needed for serialize/deserialize is the most important thing for me. Also speed is important.

Community
  • 1
  • 1
Mahdi Ghiasi
  • 14,873
  • 19
  • 71
  • 119
  • http://stackoverflow.com/questions/626766/fastest-serializer-and-deserializer-with-lowest-memory-footprint-in-c – Matthias Dec 25 '11 at 14:06
  • Questions like this (asking for opinions) are not suitable to the StackExchange format. Please ask about _specific_ programming issues (if you can't post code, it probably shouldn't be here). – Oded Dec 25 '11 at 14:07
  • @MarcGravell Please post these suggestions as an answer. and please explain more about grouped encoding and encrypted stream. Thanks a lot! – Mahdi Ghiasi Dec 25 '11 at 16:54

2 Answers2

4

If your aim is to reduce memory demands, then don't serialize then encrypt: instead - serialize directly to an encrypting Stream. The Stream API is designed to be chained (decorator pattern) to perform multiple transformations without excessive buffering. Likewise: deserialize from a decrypting stream; don't decrypt then deserialize. Done this way, data is encrypted/decrypted on-the-fly as needed; in addition to reducing memory, it is also good for security - since this also means the entire data never exists in decrypted form as a single buffer. See CryptoStream on MSDN for a full example.

Some additional notes; if you do happen to use protobuf-net, there are ways of reducing any in-memory buffering by using "grouped" encoding; you see: the default for sub-messages (including lists) is "length prefixed" - and the way it usually does this is by buffering the data in memory to calculate the length. However, protobuf also supports a format that uses a start/end marker which never requires knowing the length, so never requires buffering - and so the entire sequence can be written in a single pass direct to output (well, it does still use a buffer internally to improve IO, but it pools the buffer here, for maximum re-use). This is as simple as, for sub-objects:

[ProtoMember(11, DatFormat = DataFormat.Grouped)]
public Customer Customer {get;set;} // a sub-object

(where there is no significance in the 11)

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

See http://code.google.com/p/protobuf-net/wiki/Performance for a comparison of performance.

Matthias
  • 15,919
  • 5
  • 39
  • 84