Performance: BinaryFormatter vs. XmlSerializer

匆匆过客 提交于 2019-12-05 02:39:05
Guffa

Because you are serialising an object that doesn't have any properties.

If you serialise something different that actually contains some data, like for example a string, the binary serialiser is a lot faster than the XML serialiser.

I did this change to your code:

items.Add("asfd");

and I get this result:

Xml: 1219.0541
Bin: 165.0002

A part of the difference is of course that the XML file is about ten times larger than the binary file.

The example is pretty good and the question is interesting (I agree with Robert that you should run the Main method itself at least once before doing any measurements as initialization of variuos sorts shouldn't be considered part of the test.)

That being said, one key difference between XmlSerializer and BinaryFormatter (aside from the obvious) is that XmlSerializer makes no attempt to keep track of references. If your object graph has multiple references to the same object, you get multiple copies in the XML and this does not get resolved properly (back into a single object) upon deserialization. Worse if you have cycles, the object can't be serialized at all. Contrast this with BinaryFormatter which does keep track of references and reliably reconstructs the object graph no matter how many, and what sort of, object references you may have. Perhaps the overhead of this facility accounts for the poorer performance?

The main reason to use BinaryFormatter over XmlSerializer is the size of the output, not the performance of the serialziation/deserialization. (The overhead of constructing text is not so great, it's the transporting of that xml text that is expensive.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!