【问题标题】:BinaryFormatter becomes slower than XmlSerializer the more Items I Serialize/DeserializeBinaryFormatter 变得比 XmlSerializer 慢,我序列化/反序列化的项目越多
【发布时间】:2013-08-16 12:48:43
【问题描述】:

我有以下扩展方法来克隆包含项目的列表:

    public static class MyExtensionMethods
    {
        public static T CloneXml<T>(this T source)
        {
            var stream = new MemoryStream();
            var xmls = new XmlSerializer(typeof(T));
            xmls.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)xmls.Deserialize(stream);
        }

        public static T CloneBinary<T>(this T source)
        {
            var formatter = new BinaryFormatter();
            var stream = new MemoryStream();
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }

对于测试,我使用以下对象:

[Serializable]
public class MyItem
{
    public string Name { get; set; }
}

现在,当我克隆 100 个 MyItem 对象的列表时,BinaryFormatter 解决方案 (1ms) 将比我的 XmlSerializer 解决方案 (110ms) 快很多。 但如果列表中有 100000 个 MyItem 对象,BinaryFormatter 解决方案 (1s) 将比 XmlSerializer 解决方案 (450ms) 慢。

这是怎么回事?

【问题讨论】:

    标签: c# .net performance clone


    【解决方案1】:

    这可能是因为二进制格式化程序的性能问题已在更高的 .net 版本中修复:

    当 BinaryFormatter 遇到更大的对象列表时,它会变成二次的 由于线性搜索导致的反序列化时间

    https://github.com/dotnet/corefx/issues/16991

    然后修复:

    此修复计划包含在 .NET Framework 4.7.2 更新中。 默认情况下不会启用它。它只会在以下情况下启用 Switch.System.Runtime.Serialization.UseNewMaxArraySize 配置开关 设置好了。

    【讨论】:

      【解决方案2】:

      二进制格式对类型、程序集信息等所有元数据进行了处理。

      XMLSerializer 只是序列化为一个模式(公共字段、对象的值)。所以我认为这就是它更快的原因

      http://blogs.msdn.com/b/youssefm/archive/2009/07/10/comparing-the-performance-of-net-serializers.aspx

      【讨论】:

      • 这对我来说很有意义。谢谢。
      猜你喜欢
      • 2018-02-02
      • 2012-08-12
      • 1970-01-01
      • 2014-12-10
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      相关资源
      最近更新 更多