【问题标题】:Why is a .net generic dictionary so big为什么.net 通用字典这么大
【发布时间】:2011-02-14 07:23:22
【问题描述】:

我在 VB.net 中序列化一个通用字典,我很惊讶它大约 1.3kb 与单个项目。我做错了什么,还是我应该做其他事情?我有大量的字典,将它们全部发送到网络上让我很生气。我用于序列化的代码是

    Dim dictionary As New Dictionary(Of Integer, Integer)
    Dim stream As New MemoryStream
    Dim bformatter As New BinaryFormatter()

    dictionary.Add(1, 1)

    bformatter.Serialize(stream, dictionary)

    Dim len As Long = stream.Length

【问题讨论】:

    标签: .net vb.net generics serialization


    【解决方案1】:

    字典的默认序列化必须包含字典类型、使用的比较器以及每个项目的类型(键和值)的类型信息,因为它们通常可能是子类型。必须为每个字典添加此开销。如果将数据打印为字符串,您可以看到有很多完全限定的类型占用了大量字节:

    \0\0\0\0????\0\0\0\0\0\0\0\0\0\0?System.Collections.Generic.Dictionary2[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]\0\0\0\aVersion\bComparer\bHashSize\rKeyValuePairs\0\0\b?System.Collections.Generic.GenericEqualityComparer1[[系统.Int32,mscorlib,版本=2.0.0.0,文化=中性,PublicKeyToken=b77a5c561934e089]]\b?System.Collections.Generic.KeyValuePair2[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]][]\0\0\0\t\0\0\0\0\0\0\t\0\0\0\0\0\0?System.Collections.Generic.GenericEqualityComparer1[[System.Int32,mscorlib,版本=2.0.0.0,文化=中立,PublicKeyToken=b77a5c561934e089]]\0\0\0\0\a\0\0\0\0\0\0\0\0\0\0?System.Collections.Generic.KeyValuePair2[[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]?????System.Collections.Generic.KeyValuePair2[ [System.Int32,mscorlib,版本=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089],[System.Int32,mscorlib,版本=2.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089]]\0\0\0keyvalue \0\0\b\b\0\0\0\0\v

    您可能更喜欢使用自定义格式进行序列化,或者使用稍微轻一些的标准格式,例如JSON

    【讨论】:

      【解决方案2】:

      设置序列化字典需要大量开销(显然,大约 1.3kb ;))。但是,如果您使用原始类型作为键和值,您会发现随着更多元素添加到您的集合中,大小不会显着增长。

      此开销主要是一次性的预付费用 - 因此,一旦您将 Dictionary 类序列化,包含的成员就不会增加太多的大小。

      【讨论】:

        猜你喜欢
        • 2016-12-01
        • 2015-03-02
        • 1970-01-01
        • 1970-01-01
        • 2011-06-06
        • 1970-01-01
        • 2010-10-06
        • 2013-05-11
        • 2012-10-22
        相关资源
        最近更新 更多