This library, also available via Nuget, provides the FastBinaryFormatter
class, an IFormatter
implementation as a replacement for the standard BinaryFormatter for serialization purposes. It has the following features:
- It has a higher upper limit for the number of objects being serialized. The standard BinaryFormatter has a limit of ~13.2 million objects. The FastBinaryFormatter limits 2^31 reference-type instances and poses no limits to value-type instances.
- It runs faster and is less memory-demanding, especially during deserialization.
- Serialization streams typically have smaller size compared to the ones produced by BinaryFormatter and they are not compatible.
- Serialization streams are portable between 32 bit and 64 bit applications.
- Relies on the standards. As a consequence, existing serializable classes, like those in the .NET base class library, need no change. Specifically, it supports:
SerializableAttribute
NonSerializedAttribute
OptionalFieldAttribute
OnSerializingAttribute
OnSerializedAttribute
OnDeserializingAttribute
OnDeserializedAttribute
ISerializable
IDeserializationCallback
IObjectReference
ISerializationSurrogate
The significant performance gain comes at the cost of not supporting a very specific scenario:
During deserialization, if a registered
ISerializationSurrogate
returns in methodSetObjectData
a (non-null) different object than the one supplied to populate, then the data supplied in theSerializationInfo
must not recursively cause a deserialization cycle up to the new object. A cycle is allowed though if it is established outside the deserialized objects. In particular, cycles formed by associations created by other surrogates are allowed.
The same restriction applies to
IObjectReference
implementations.
Note that support for returning a different non-null object in method
SetObjectData
has effect in version .NET 2.0 and later. The return value was previously ignored.
This scenario is highly unlikely to be found in practice. However, it is detected during deserialization and an exception is thrown upon occurrence.
The library has no dependencies.
##Example usage
Using FastBinaryFormatter
is same as built-in .NET serialization formatters.
Album[] serializedObject = BuildAlbumArray(); // Example object graph.
var formatter = new FastBinaryFormatter();
// If required, define surragate selectors.
var surrogateSelector = new SurrogateSelector();
surrogateSelector.AddSurrogate(typeof(Genre), new StreamingContext(), new GenreSerializationSurrogate());
formatter.SurrogateSelector.ChainSelector(surrogateSelector);
using (var stream = new MemoryStream())
{
// Serialize.
formatter.Serialize(stream, serializedObject);
stream.Seek(0, SeekOrigin.Begin);
// Deserialize.
var deserializedObject = (Album[])formatter.Deserialize(stream);
}