我正在使用一个应用程序,需要在文件中存储40,000多个键和值的大型词典,然后在启动时将它们加载回字典...现在我正在使用一个简单的字符分隔与分割和a启动时的每个循环,如:
key1=value1|key2=value2|key3=value3
等......
然而,我正在寻找一种更有效的序列化和反序列化词典的方法......同时考虑到序列化数据的大小,因为有很多条目。
答案 0 :(得分:3)
您可以使用BinaryFormatter
在我的中端机器上:保存花了:390ms加载:359ms保存的数据大约是1500kb
'save
Dim dict = New Dictionary(Of String, String)
For i = 1 To 40000
dict.Add("key" & i, "value" & i)
Next
Dim fs As IO.FileStream = New IO.FileStream("d:\test\test.bin", IO.FileMode.OpenOrCreate)
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
bf.Serialize(fs, dict)
fs.Close()
'load
Dim fsRead As New IO.FileStream("d:\test\test.bin", IO.FileMode.Open)
Dim objTest As Dictionary(Of String, String) = bf.Deserialize(fsRead)
fsRead.Close()
答案 1 :(得分:0)
使用堆叠词典时效果很好:
Dim DataDict as New Dictionary(Of String,Dictionary(Of String,String))
以下是为编写和阅读而序列化的嵌入式词典的工作示例:
Imports System.IO
Module Modules
Public Sub TestDict()
Dim DictsToSave As New Dictionary(Of String, Dictionary(Of String, String))
For DictsToHave = 1 To 10
Dim SingelDictData As New Dictionary(Of String, String)
For Values = 1 To 10000
SingelDictData.Add("Key " & Values.ToString(), "Value " & Values.ToString())
Next
DictsToSave.Add("Key " & DictsToHave.ToString(), SingelDictData)
Next
Dim WriteResult = WriteMultiSerializedDict("D:\TestDict.Bin", DictsToSave)
Dim ReadResult As Dictionary(Of String, Dictionary(Of String, String)) = ReadMultiSerializedDict("D:\TestDict.Bin")
End Sub
Public Function WriteMultiSerializedDict(ByVal FullPath As String, ByVal DataDict As Dictionary(Of String, Dictionary(Of String, String))) As Boolean
Try
Dim FileStream As IO.FileStream = New FileStream(FullPath, IO.FileMode.OpenOrCreate)
Dim BinFormatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
BinFormatter.Serialize(FileStream, DataDict)
FileStream.Close()
Return True
Catch ex As Exception
Return False
End Try
End Function
Public Function ReadMultiSerializedDict(ByVal FullPath As String) As Dictionary(Of String, Dictionary(Of String, String))
Try
Dim DataDict As New Dictionary(Of String, Dictionary(Of String, String))
Dim FileStream As IO.FileStream = New FileStream(FullPath, IO.FileMode.Open)
Dim BinFormatter As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
DataDict = BinFormatter.Deserialize(FileStream)
FileStream.Close()
Return DataDict
Catch ex As Exception
Return Nothing
End Try
End Function
在我的中端开发机器上,写入需要大约260毫秒,读取大约需要545毫秒,文件大小为3.70 MB。重要提示:如果您更改了任何dict的键(而不是值),那么装载炸弹就会出现!因此,作为编程问题,请始终按相同顺序组合您的dicts。我之前使用过这种方法,在子词典中使用5 100个键/值对,没有问题或者问题。