Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Serialisation - When To Use DataContractSerializer / Binary / XMLSerialiser

I ve been looking at this for a while now

It seems that binary serialisation is discouraged as any change to field names breaks serialisation =? Not Good

XMLSerializer is problematic because you have to provide a no arg constructor and public fields although you do have more control over elements being attributes or elements and their naming

DataContractSerializer is good but all suclassses need to be explicitly added which is a shame

However I stumbled across NetDataContractSerializer which does not have this limitation.

If your goal is C# serialisation and no big constraints on size of xml is NetDataContractSerializer always the way to go here??

like image 557
Jack Kada Avatar asked Dec 29 '09 21:12

Jack Kada


2 Answers

Dan Rigsby has a really good comparative article on XmlSerializer vs. DataContractSerializer and also touches on the NetDataContractSerializer.

DataContractSerializer:

  • it's fast - around 10% faster than XmlSerializer
  • it's interoperable - works flawlessly with Java, Ruby - you name it
  • uses explicit "opt-in" model - you need to mark what gets serialized
  • doesn't require any constructor
  • can serialize non-public members and internal fields
  • doesn't support attributes on XML nodes

You tell the DCS explicitly what to serialize, but you don't have much influence over how it's done.

XmlSerializer

  • serializes only public fields and properties
  • serializes everything except those you exclude (opt-out model)
  • support attributes and everything
  • it's interoperable - works flawlessly with Java, Ruby - you name it
  • requires a parameterless constructor for deserialization

You tell the XmlSerializer pretty clearly how and what to serialize, but you cannot serialize everything - only publicly visible properties.

The NetDataContractSerializer is a bit of an oddity - it's not interoperable, it works only if both ends are .NET - it includes .NET type information into the message (making it bigger). You cannot add it declaratively to a WCF service "out of the box".

It's a tough trade-off - as always. Definitely stay away from any binary formatter - that's not backwards compatible, brittle, and bound to give you headaches - use one of those standard ways of doing it. Which one is the "best" for your given scenario is really hard to tell - you'll have to figure that one out for yourself....

like image 125
marc_s Avatar answered Oct 09 '22 14:10

marc_s


Marc Gravell shows on his blog the results of a benchmark he did with DataContractSerializer, XmlSerializer, and most of the other .NET serializers around, including protobuf-net (an implementation of Protocol Buffers for .NET he created).

like image 38
Fabrice Avatar answered Oct 09 '22 14:10

Fabrice