. Net (C #): Use binaryformatter. unsafedeserialize to increase deserialization Performance

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.