C# Json和Xml序列化,哪个性能更好?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10916591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Json and Xml serialization, what is better performance?
提问by Yara
I have to store some config info in file. In C# code config data represents by class and in file I am going to save this class in json or xml format. So, what is the best performance of serialization json or xml?
我必须在文件中存储一些配置信息。在 C# 代码配置数据按类和文件表示,我将把这个类保存为 json 或 xml 格式。那么,序列化json或xml的最佳性能是什么?
采纳答案by Wedge
Well instead of guessing, I have the answer. Here is the test program:
好吧,而不是猜测,我有答案。下面是测试程序:
class Program
{
static void Main(string[] args)
{
string xmlConfig = "";
string jsonConfig = "";
Config myConfig = new Config()
{
value = "My String Value",
DateStamp = DateTime.Today,
counter = 42,
Id = Guid.NewGuid()
};
// Make both strings
DataContractSerializer xmlSerializer = new DataContractSerializer(typeof(Config));
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.WriteObject(xmlStream, myConfig);
xmlConfig = Encoding.UTF8.GetString(xmlStream.ToArray());
}
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Config));
using (MemoryStream jsonStream = new MemoryStream())
{
jsonSerializer.WriteObject(jsonStream, myConfig);
jsonConfig = Encoding.UTF8.GetString(jsonStream.ToArray());
}
// Test Single
var XmlSingleTimer = Stopwatch.StartNew();
SerializeXML(xmlConfig, 1);
XmlSingleTimer.Stop();
var JsonSingleTimer = Stopwatch.StartNew();
SerializeJSON(jsonConfig, 1);
JsonSingleTimer.Stop();
// Test 1000
var XmlTimer = Stopwatch.StartNew();
SerializeXML(xmlConfig, 1000);
XmlTimer.Stop();
var JsonTimer = Stopwatch.StartNew();
SerializeJSON(jsonConfig, 1000);
JsonTimer.Stop();
// Test 10000
var XmlTimer2 = Stopwatch.StartNew();
SerializeXML(xmlConfig, 10000);
XmlTimer2.Stop();
var JsonTimer2 = Stopwatch.StartNew();
SerializeJSON(jsonConfig, 10000);
JsonTimer2.Stop();
Console.WriteLine(String.Format("XML Serialization Single: {0}ms", XmlSingleTimer.Elapsed.TotalMilliseconds));
Console.WriteLine(String.Format("JSON Serialization Single: {0}ms", JsonSingleTimer.Elapsed.TotalMilliseconds));
Console.WriteLine();
Console.WriteLine(String.Format("XML Serialization 1000: {0}ms", XmlTimer.Elapsed.TotalMilliseconds));
Console.WriteLine(String.Format("JSON Serialization 1000: {0}ms ", JsonTimer.Elapsed.TotalMilliseconds));
Console.WriteLine();
Console.WriteLine(String.Format("XML Serialization 10000: {0}ms ", XmlTimer2.ElapsedMilliseconds));
Console.WriteLine(String.Format("JSON Serialization 10000: {0}ms ", JsonTimer2.ElapsedMilliseconds));
}
public static void SerializeXML(string xml, int iterations)
{
DataContractSerializer xmlSerializer = new DataContractSerializer(typeof(Config));
for (int i = 0; i < iterations; i++)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
Config serialized = (Config)xmlSerializer.ReadObject(stream);
}
}
}
public static void SerializeJSON(string json, int iterations)
{
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Config));
for (int i = 0; i < iterations; i++)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
Config serialized = (Config)jsonSerializer.ReadObject(stream);
}
}
}
}
public class Config
{
public string value;
public DateTime DateStamp;
public int counter;
public Guid Id;
}
And this is the measured output:
这是测量的输出:
XML Serialization Single: 2.3764ms
JSON Serialization Single: 2.1432ms
XML Serialization 1000: 13.7754ms
JSON Serialization 1000: 13.747ms
XML Serialization 10000: 100ms
JSON Serialization 10000: 134ms
JSON consistently came out just a tiny bit faster after 1 iteration. After 1000 iterations there really was no difference. After 10000 iterations, XML was clearly faster.
在 1 次迭代后,JSON 的输出速度始终快一点。经过 1000 次迭代后,确实没有区别。在 10000 次迭代之后,XML 显然更快了。
At this point I can't explain why JSON would be faster one at a time, but XML would be faster when it is repeated. Possibly due to caching or something fancy in the library. You can see that the JsonSerializer scaled linearly, increasing the iterations by an order of 10 linearly increased the elapsed time by an order of 10. The XmlSerializer behaved differently though, its performance did not scale in a linear way.
在这一点上,我无法解释为什么 JSON 一次一个会更快,但 XML 在重复时会更快。可能是由于缓存或库中的一些花哨的东西。您可以看到 JsonSerializer 线性扩展,将迭代次数增加 10 次,使运行时间线性增加 10 次。尽管 XmlSerializer 表现不同,但其性能并未以线性方式扩展。
I repeated this several times and consistently got the same results.
我重复了几次,并始终得到相同的结果。
So, the lesson is if you are just parsing a single object one time, then JSON will be slightly better. But if you are repeatedly parsing objects, then XML might perform better. Although, I haven't tested what would happen if the object values change with each iteration, that might make a difference.
因此,教训是,如果您只是一次解析单个对象,那么 JSON 会稍微好一点。但是,如果您重复解析对象,那么 XML 的性能可能会更好。虽然,我还没有测试如果对象值随着每次迭代而改变会发生什么,这可能会有所不同。
Also note, I am using the native Runtime.Serialization library here. Other libraries will likely produce different results.
另请注意,我在这里使用本机 Runtime.Serialization 库。其他库可能会产生不同的结果。
Edit: I just tried this while generating a new Guid and random Int every time the strings are called. It made no difference to the single or 10000 iteration tests. But for 1000 iterations, JSON was about 1ms faster. So it seems like the XML serializer really is caching the values.
编辑:我只是在每次调用字符串时生成新的 Guid 和随机 Int 时尝试过这个。它对单次或 10000 次迭代测试没有影响。但是对于 1000 次迭代,JSON 快了大约 1 毫秒。所以看起来 XML 序列化程序确实在缓存这些值。
回答by Oleksi
The cost to serialize would be roughly the same. It's unlikely to be a noticeable difference. Use the format that your users will feel most comfortable modifying (since it's a config file).
序列化的成本大致相同。这不太可能是一个明显的差异。使用您的用户最愿意修改的格式(因为它是一个配置文件)。
The real performance difference might happen when you need to send the JSON or XML across a network. Then, the performance depends on how much stuff you're sending, and since JSON is usually more concise than XML, it will generally perform better over a network.
当您需要通过网络发送 JSON 或 XML 时,可能会出现真正的性能差异。然后,性能取决于您发送多少内容,并且由于 JSON 通常比 XML 更简洁,因此它通常在网络上的性能更好。
回答by Andrei Neagu
Json can be somethimes less readable by humans than xml, but the size of the file generated by json is smaller. So if you need to send the file over network, Json may be the better choise, or if you want to be able to read it, XML is better. Another good thing, is that in .NET 4 you have the dynamic keyword, and you can convert your Json directly to a C# object.
Json 有时比 xml 更不易被人类阅读,但 json 生成的文件的大小更小。因此,如果您需要通过网络发送文件,Json 可能是更好的选择,或者如果您希望能够读取它,XML 更好。另一个好处是,在 .NET 4 中,您有 dynamic 关键字,您可以将 Json 直接转换为 C# 对象。
回答by Adam Houldsworth
When I go looking for configuration in a .NET application, I expect to find an XML file somewhere called MyApp.exe.config.
当我在 .NET 应用程序中寻找配置时,我希望在某处找到一个名为 MyApp.exe.config 的 XML 文件。
Sticking with the principle of least surpriseI would favour XML serialization over JSON. There is an added benefit that XML formatted configuration can be adapted to work with the Configuration API. Both otherwise have the same sort of support: platform agnostic, decent parsers, text-based, etc.
坚持最小意外的原则,我更喜欢 XML 序列化而不是 JSON。可以调整 XML 格式的配置以与配置 API一起使用还有一个额外的好处。否则两者都具有相同的支持:平台不可知、体面的解析器、基于文本等。
Performance is only an issue when it becomes an issue. I am a fan of identifying potential issues before I code them, but that is usually on performance issues introduced by architectural decisions. Something like this, small and fairly self-contained, won't be difficult to change if it proves to be a problem under profiling.
只有当性能成为问题时,性能才会成为问题。我喜欢在编码之前识别潜在问题,但这通常是关于架构决策引入的性能问题。像这样的东西,小而且相当独立,如果在分析中被证明是一个问题,它不会很难改变。
回答by Joel Santos
in my opinion all is depend what you need to do and how to you want implement, here is a good article comparing JSON and XML. compression and deserialization in client side I choose JSON.
在我看来,一切都取决于您需要做什么以及如何实现,这是一篇比较 JSON 和 XML 的好文章。客户端的压缩和反序列化我选择 JSON。
Good Luck.
祝你好运。
http://dotnet.dzone.com/articles/json-vs-xml-net-developer%E2%80%99s
http://dotnet.dzone.com/articles/json-vs-xml-net-developer%E2%80%99s

