From what I understand, the BinaryFormatter + StreamWriter combo can become pretty slow and bloated because it adds metadata to the byte array about the object or file, properties, and datatypes.
One option you have, if you are willing to work with a third party library, is Protocol Buffers. According to the site, it is lightweight, fast serialization format that Google uses in their data communications. It's also recommended in this StackOverflow question: Fast and compact object serialization in .NET.
There are two libraries are available for .NET:
Here is a table of results comparing "protobuf-net" (first link) and "proto#" (second link) to other serialization techniques (more tests available here):
Serializer size serialize deserialize
-------------------------------------------------------------
protobuf-net 3 268 1,881
proto# 3 76 1,792
BinaryFormatter 153 6,694 8,420
SoapFormatter 687 28,609 55,125
XmlSerializer 153 14,594 19,819
DataContractSerializer 205 3,263 10,516
DataContractJsonSerializer 26 2,854 15,621
If you would prefer to have a little more control over it, though, (and if you are just serializing objects), then this link from Code Project contains a neat pattern for serializing them: http://www.codeproject.com/Articles/14164/A-Fast-Serialization-Technique
The idea is that you implement the ISerializable
interface for whatever class you need to serialize. This forces you to add a the ISerializable.GetObjectData
method, which provides a SerializationWriter
that you use to write each property individually, which you then add to a SerializationInfo
object. The syntax itself for this is actually incredibly straightforward.
Here is a quick, abbreviated, sample of the GetObjectData
method from the site:
// Serialize the object. Write each field to the SerializationWriter
// then add this to the SerializationInfo parameter
public void GetObjectData (SerializationInfo info, StreamingContext ctxt) {
SerializationWriter sw = SerializationWriter.GetWriter ();
sw.Write (id1);
sw.Write (id2);
sw.Write (id3);
sw.Write (s1);
sw.Write (s2);
// more properties here
sw.AddToInfo (info);
}
Here are the results of this author's tests:
Formatter Size (bytes) Time (uS)
--------------------------------------------------------------------
Standard serialization Binary 2080 364
Fast serialization Binary 421 74
Fast serialization SOAP 1086 308