Json和Xml序列化有什么更好的性能? [英] Json and Xml serialization, what is better performance?

查看:213
本文介绍了Json和Xml序列化有什么更好的性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在文件中存储一些配置信息.在C#代码中,配置数据按类表示,在文件中,我将以json或xml格式保存此类.那么,序列化json或xml的最佳性能是什么?

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?

推荐答案

好吧,我没有答案.这是测试程序:

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;
}

这是测得的输出:

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在经过1次迭代后始终稳定地以更快的速度出现.经过1000次迭代后,实际上没有任何区别.经过10000次迭代,XML明显更快.

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.

在这一点上,我无法解释为什么JSON一次会更快,但是XML重复一次会更快.可能是由于缓存或库中某些内容所致. 您可以看到JsonSerializer线性缩放,将迭代增加10数量级,线性增加将经过的时间增加10数量级.XmlSerializer的行为有所不同,但它的性能并未以线性方式缩放.

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.

我重复了几次,一直得到相同的结果.

I repeated this several times and consistently got the same results.

因此,教训是,如果您一次只解析一个对象,那么JSON会稍微好一些.但是,如果您反复分析对象,那么XML可能会表现更好.虽然,我还没有测试如果每次迭代对象值都发生变化会发生什么,那可能会有所不同.

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.

还请注意,我在这里使用本机Runtime.Serialization库.其他库可能会产生不同的结果.

Also note, I am using the native Runtime.Serialization library here. Other libraries will likely produce different results.

每次调用字符串时,我都在生成新的Guid和random Int时进行了尝试.它对单次或10000次迭代测试没有影响.但是对于1000次迭代,JSON的速度提高了大约1毫秒.因此,看起来XML序列化程序确实在缓存值.

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.

这篇关于Json和Xml序列化有什么更好的性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆