性能:BinaryFormatter与XmlSerializer [英] Performance: BinaryFormatter vs. XmlSerializer
问题描述
我经常读到BinaryFormatter比XmlSerializer具有更好的性能. 出于好奇,我编写了一个测试应用.
I read very often that the BinaryFormatter has better performance then XmlSerializer. Out of curiosity, I wrote a test-app.
一个wtf时刻...为什么Xml比Bin快得多(尤其是反序列化)?
a wtf moment... why is Xml so much faster than Bin (especially the deserialization)?
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace SerPlayground
{
class Program
{
static void Main(string[] args)
{
var items = new List<TestClass>();
for (int i = 0; i < 1E6; i++)
{
items.Add(new TestClass() { Name = i.ToString(), Id = i });
}
File.Delete("test.bin");
using (var target = new FileStream("test.bin", FileMode.OpenOrCreate))
{
System.Threading.Thread.Sleep(1000);
var bin = new BinaryFormatter();
var start = DateTime.Now;
bin.Serialize(target, items);
Console.WriteLine("Bin: {0}", (DateTime.Now - start).TotalMilliseconds);
target.Position = 0;
System.Threading.Thread.Sleep(1000);
start = DateTime.Now;
bin.Deserialize(target);
Console.WriteLine("Bin-D: {0}", (DateTime.Now - start).TotalMilliseconds);
}
File.Delete("test.xml");
using (var target = new FileStream("test.xml", FileMode.OpenOrCreate))
{
System.Threading.Thread.Sleep(1000);
var xml = new XmlSerializer(typeof(List<TestClass>));
var start = DateTime.Now;
xml.Serialize(target, items);
Console.WriteLine("Xml: {0}", (DateTime.Now - start).TotalMilliseconds);
target.Position = 0;
System.Threading.Thread.Sleep(1000);
start = DateTime.Now;
xml.Deserialize(target);
Console.WriteLine("Xml-D: {0}", (DateTime.Now - start).TotalMilliseconds);
}
Console.ReadKey();
}
}
[Serializable]
public class TestClass
{
public string Name { get; set; }
public int Id { get; set; }
}
}
我的结果:
Bin: 13472.7706
Bin-D: 121131.9284
Xml: 8917.51
Xml-D: 12841.7345
推荐答案
因为您要序列化没有任何属性的对象.
Because you are serialising an object that doesn't have any properties.
如果您序列化实际上包含某些数据的其他内容(例如字符串),则二进制序列化程序要比XML序列化程序快得多.
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");
我得到这个结果:
Xml: 1219.0541
Bin: 165.0002
部分差异当然是XML文件比二进制文件大大约十倍.
A part of the difference is of course that the XML file is about ten times larger than the binary file.
这篇关于性能:BinaryFormatter与XmlSerializer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!