Json和Xml序列化,哪个性能更好?

2024-03-02

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


好吧,我没有猜测,而是有了答案。这是测试程序:

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

在 1 次迭代后,JSON 的速度始终快了一点点。经过 1000 次迭代后,确实没有什么区别。经过 10000 次迭代后,XML 明显更快。

在这一点上,我无法解释为什么 JSON 一次会更快,但 XML 在重复时会更快。可能是由于缓存或库中的一些奇特的东西。 您可以看到 JsonSerializer 呈线性扩展,迭代次数增加了 10 个数量级,运行时间也线性增加了 10 个数量级。尽管 XmlSerializer 的行为有所不同,但其性能并未以线性方式扩展。

我重复了几次并且始终得到相同的结果。

所以,教训是,如果您只是解析一次单个对象,那么 JSON 会稍微好一些。但如果您重复解析对象,那么 XML 可能会表现得更好。虽然,我还没有测试如果对象值随着每次迭代而改变会发生什么,但这可能会产生影响。

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

编辑:我只是在每次调用字符串时生成新的 Guid 和随机 Int 时尝试了此操作。这对单次或 10000 次迭代测试没有影响。但对于 1000 次迭代,JSON 大约快了 1 毫秒。所以看起来 XML 序列化程序确实在缓存这些值。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Json和Xml序列化,哪个性能更好? 的相关文章

  • pthread_cond_timedwait() 和 pthread_cond_broadcast() 解释

    因此 我在堆栈溢出和其他资源上进行了大量搜索 但我无法理解有关上述函数的一些内容 具体来说 1 当pthread cond timedwait 因为定时器值用完而返回时 它如何自动重新获取互斥锁 互斥锁可能被锁定在其他地方 例如 在生产者
  • 从父类调用子类方法

    a doStuff 方法是否可以在不编辑 A 类的情况下打印 B did stuff 如果是这样 我该怎么做 class Program static void Main string args A a new A B b new B a
  • linux perf:如何解释和查找热点

    我尝试了linux perf https perf wiki kernel org index php Main Page今天很实用 但在解释其结果时遇到了困难 我习惯了 valgrind 的 callgrind 这当然是与基于采样的 pe
  • 为什么#pragma optimize("", off)

    我正在审查一个 C MFC 项目 在某些文件的开头有这样一行 pragma optimize off 我知道这会关闭所有以下功能的优化 但这样做的动机通常是什么 我专门使用它来在一组特定代码中获得更好的调试信息 并在优化的情况下编译应用程序
  • 如何使用shell脚本从json字符串中grep特定字段值[重复]

    这个问题在这里已经有答案了 下面是文件中可用的 JSON 字符串 我需要从中提取值status在 shell 脚本中 预期输出 status success 响应 json eventDate null dateProccessed nul
  • 如何将图像和 POST 数据上传到 Azure 移动服务 ApiController 终结点?

    我正在尝试上传图片and POST表单数据 尽管理想情况下我希望它是json 到我的端点Azure 移动服务应用 我有ApiController method HttpPost Route api upload databaseId sea
  • 指针减法混乱

    当我们从另一个指针中减去一个指针时 差值不等于它们相距多少字节 而是等于它们相距多少个整数 如果指向整数 为什么这样 这个想法是你指向内存块 06 07 08 09 10 11 mem 18 24 17 53 7 14 data 如果你有i
  • 包含 contains 的 json 格式查询

    我在 ansible 中有以下 json 输出 active transaction null cores 4 hostname alpha auth wb01 active transaction null cores 4 hostnam
  • vector 超出范围后不清除内存

    我遇到了以下问题 我不确定我是否错了或者它是一个非常奇怪的错误 我填充了一个巨大的字符串数组 并希望在某个点将其清除 这是一个最小的例子 include
  • 当操作繁忙时,表单不执行任何操作(冻结)

    我有一个使用 C 的 WinForms 应用程序 我尝试从文件中读取一些数据并将其插入数据表中 当此操作很忙时 我的表单冻结并且无法移动它 有谁知道我该如何解决这个问题 这可能是因为您在 UI 线程上执行了操作 将文件和数据库操作移至另一个
  • dbms_xmlgen.getxml - 如何设置日期格式

    我们使用 dbms xmlgen getxml 实用程序通过 SQL 查询生成 xml 该查询从几乎 10 15 个相关表中获取数据 默认情况下 日期格式生成于dd MMM yy格式 有什么方法可以在 dbms xmlgen getxml
  • 实体框架 4 DB 优先依赖注入?

    我更喜欢创建自己的数据库 设置索引 唯一约束等 使用 edmx 实体框架设计器 从数据库生成域模型是轻而易举的事 现在我有兴趣使用依赖注入来设置一些存储库 我查看了 StackOverflow 上的一些文章和帖子 似乎重点关注代码优先方法
  • 插入记录后如何从SQL Server获取Identity值

    我在数据库中添加一条记录identity价值 我想在插入后获取身份值 我不想通过存储过程来做到这一点 这是我的代码 SQLString INSERT INTO myTable SQLString Cal1 Cal2 Cal3 Cal4 SQ
  • C++ fmt 库,仅使用格式说明符格式化单个参数

    使用 C fmt 库 并给定一个裸格式说明符 有没有办法使用它来格式化单个参数 example std string str magic format 2f 1 23 current method template
  • 需要哪个版本的 Visual C++ 运行时库?

    microsoft 的最新 vcredist 2010 版 是否包含以前的版本 2008 SP1 和 2005 SP1 还是我需要安装全部 3 个版本 谢谢 你需要所有这些
  • 如何让Gtk+窗口背景透明?

    我想让 Gtk 窗口的背景透明 以便只有窗口中的小部件可见 我找到了一些教程 http mikehearn wordpress com 2006 03 26 gtk windows with alpha channels https web
  • const、span 和迭代器的问题

    我尝试编写一个按索引迭代容器的迭代器 AIt and a const It两者都允许更改容器的内容 AConst it and a const Const it两者都禁止更改容器的内容 之后 我尝试写一个span
  • Validation.ErrorTemplate 的 Wpf 动态资源查找

    在我的 App xaml 中 我定义了一个资源Validation ErrorTemplate 这取决于动态BorderBrush资源 我打算定义独特的BorderBrush在我拥有的每个窗口以及窗口内的不同块内
  • ASP.NET MVC 6 (ASP.NET 5) 中的 Application_PreSendRequestHeaders 和 Application_BeginRequest

    如何在 ASP NET 5 MVC6 中使用这些方法 在 MVC5 中 我在 Global asax 中使用了它 现在呢 也许是入门班 protected void Application PreSendRequestHeaders obj
  • 防止索引超出范围错误

    我想编写对某些条件的检查 而不必使用 try catch 并且我想避免出现 Index Out of Range 错误的可能性 if array Element 0 Object Length gt 0 array Element 1 Ob

随机推荐