First, because this method uses linkdemand to check the securitypermissionattribute. serializationformatter permission, it may not be available in some trusted environments. This method has better performance than the deserialize method.
Code:
// + Using system. runtime. serialization. formatters. Binary
// + Using system. IO;
// Create a dictionary with 100 Elements
VaR DIC = new dictionary <int, string> ();
For (INT I = 0; I <100; I ++)
Dic. Add (I, I. tostring ());
// Serialize to a file
VaR BF = new binaryformatter ();
VaR stream = new filestream (path. gettempfilename (), filemode. Create, fileaccess. readwrite );
BF. serialize (stream, DIC );
Stream. Seek (0, seekorigin. Begin );
// Use deserialize for deserialization
VaR stopwatch = stopwatch. startnew ();
BF. deserialize (Stream );
Console. writeline (stopwatch. elapsed );
// Use unsafedeserialize for deserialization
Stream. Seek (0, seekorigin. Begin );
Stopwatch. Restart ();
BF. unsafedeserialize (stream, null );
Console. writeline (stopwatch. elapsed );
The performance improvement of unsafedeserialize is related to the structure and size of the serialized object.
For example, the dictionary results of the 100 elements in the example:
00:00:00. 0015032
00:00:00. 0004704
The performance of the 10 elements varies significantly:
00:00:00. 0010952
00:00:00. 0001489
The difference between the 1000 elements is not very big:
00:00:00. 0045790
00:00:00. 0036886