為什麼.net 通用字典這麼大
我在 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
字典的預設序列化必須包含字典類型、使用的比較器以及每個項目的類型(鍵和值)的類型資訊,因為它們通常可能是子類型。必須為每個字典添加此成本。如果將數據列印為字元串,您會看到有很多完全限定的類型占用了大量字節:
\0\0\0\0????\0\0\0\0\0\0\0\0\0\0?System.Collections.Generic.Dictionary
2[[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$$ [System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 $$]\b?System.Collections.Generic.KeyValuePair
2[[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, Version=2.0.0.0, Culture=neutral, 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, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 $$,$$ System.Int32, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 $$]\0\0\0鍵值\0\0\b\b\0\0\0\0\v您可能更喜歡使用自定義格式進行序列化,或者使用稍微輕一些的標準格式,例如JSON。