XmlSerializer, DataContractSerializer and BinaryFormatter differences and usage analysis

Source: Internet
Author: User

. NET provides a lot of methods for serializing objects, knowing the difference between them to better determine which serialization method to use and use correctly. In this paper, three kinds of serialization methods in the title are analyzed from the following aspects.

    • Range: property or Field or Both
    • Visibility of: Public or Private or all
    • Accessibility : Readonly Property
    • callback: refers to OnSerializing, OnSerialized, OnDeserializing, ondeserialized these callbacks.
    • objects that contain circular references
    • objects that contain dictionary
    • Disorderly Read (XML)
    • Custom serialization results.
    • There is no attribute requirement for the serialized class. Sometimes the serialized object is in a third-party library, the source code cannot be modified, and if you want to serialize such an object, you cannot use a serializer that must have attribute.

First the results of the analysis: The code can be downloaded from here, the written test may not be comprehensive, so if there are any errors, welcome to point out, or to fraught. But with this more fraught article at the bottom of the hall (Google top 1), I believe this watch will not be worse.

XmlSerializer DataContractSerializer BinaryFormatter
Range Both Both Field only
Visibility of Public only All All
Read-only properties Not supported Support, but to add attribute N/A
Callback Support Not supported Support Support
Circular references Not supported Support, but to add attribute Support
Dictionary Not supported Supported, proprietary formats Support
Disorderly sequence Reading Support Not supported Not supported
Custom formats Support, to add attribute XML Attribute not supported Via interface
Attribute requirements Not necessary Not necessary There must be serializable.

There are a few things to explain.

Performance? Size?

In several test cases I wrote, the performance and size of these serializer are basically at an order of magnitude, whether for simple objects, nested objects, or arrays of repeated reference objects. Their functional differences are much larger than their performance differences. At this point, the decision to use which method should depend on the function and its constraints, not the performance. If you care about performance, you should use a third-party library, such as Google's protobuf-net. No matter from performance, the size of the serialization results, or compatibility, protobuf-net is superior to all three, and of course, not human readable.

Attribute requirements

Many similar articles claim that XmlSerializer and DataContractSerializer are required to add the corresponding attribute on the class. But that's not the truth. attribute is only necessary if you want to change the default serialization results.

One of the most common mistakes is to add serializable Attribute to the class XmlSerializer to use. This attribute is actually for BinaryFormatter and SoapFormatter use, generally used in remoting and messaging.

Disorderly sequence Reading

Disorderly reading means that the sequence of XML nodes is not required in the deserialize process. XML itself is a markup, declarative language, and most XML-based network protocols do not require the order of the XML nodes. such as the common Rss,atom,opds and so on.

The DataContractSerializer used by WCF requires that the XML node order be either strictly specified or alphabetically, perhaps with performance considerations, But WCF's positioning is the root cause of allowing DataContractSerializer to be strict with the order of XML nodes. WCF itself is used for communication, its positioning of the serialization, just a means of message delivery, the strict definition of the message format is nothing bad, and the caller's code can be generated through WSDL, and naturally there is no problem when parsing. Therefore, it is entirely up to the function setting to not support disorderly sequence reading.

XmlSerializer, in my opinion, can be used as an object XML mapping tool, of course, to support all XML standards as much as possible.

Custom Support

Both XmlSerializer and DataContractSerializer support the Ixmlserializer interface. Through this interface DataContractSerializer can even support attribute, but this is not actually using the DataContractSerializer serialization mechanism. It is also not operable in actual projects. So in the table above, the DataContractSerializer is marked as not supporting XML Attribute.

There are also some common interfaces, such as ISerializable and Ideserializationcallback, that are used for BinaryFormatter to support the process of customizing serialization. I'm surprised here. For BinaryFormatter has supported OnDeserialized Attribute, why there is such an interface to provide similar functionality.

Some little details.

Two XML serialization methods there are some small interesting differences, I try to guess the reasons for this difference, but I did not think of it, perhaps some of the Microsoft employees are not known design ideas, perhaps just write code when the liking.

    1. XmlSerializer does not serialize null values, and DataContractSerializer serializes null values by default.
    2. DataContractSerializer and attribute: Serializes all public readable writable property and field for classes without any attribute, and for classes that simply add serializable attribute, Serialize all the visibility of the field (in order to be consistent with binaryformatter behavior); If only add DataContract Attribute, then nothing will be serialized out, must add DataMember.
    3. The DataContract supports sequential read-only properties, but the attributes are added DataMember.
    4. DataContractSerializer, only add DataMember without datacontract will be abnormal.
    5. The DataContractSerializer is incompatible with the ISerializable interface and throws the exception directly.
    6. DataContractSerializer support Ixmlserializer interface, but this interface is implemented, it can not add datacontract. Otherwise, throw an exception. What is the reason?
    7. The cost of XmlSerializer support for disorderly reading is that you cannot control the order of the nodes of your own generated XML. That is, the order cannot be specified in ElementName attribute.
    8. BinaryFormatter requires that the class be serialized must be "serializable". So if you can't change the source code, serialization is not serializable. And xmlserializable, you can serialize the property of internal and protected in the way of inheritance.
Summary

Based on the objective results above, I believe you have your own judgment. My personal opinion, datacontractserializable is used in the place where it should be used, if not with WCF, or do not use it, its serialization results have some Microsoft-specific things. XmlSerializer is the perfect choice for loose XML interface data from the network. If you want to keep the object intact (data and state), you don't need to be looked at at the same time. Then use BinaryFormatter. If the performance or data size requirements are relatively high, then these three can be used, with Protobuff bar.

Add

This information is a kind of experience, but it is definitely not suitable for cooperative interview or written questions.

XmlSerializer, DataContractSerializer and BinaryFormatter differences and usage analysis

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.