interesting question. I did some quick tests and you are right - BinaryFormatter is surprisingly slow:
- Serialize 130,000 dictionary entries: 547ms
- Deserialize 130,000 dictionary entries: 1046ms
When I coded it with a StreamReader/StreamWriter with comma separated values I got:
- Serialize 130,000 dictionary entries: 121ms
- Deserialize 130,000 dictionary entries: 111ms
But then I tried just using a BinaryWriter/BinaryReader:
- Serialize 130,000 dictionary entries: 22ms
- Deserialize 130,000 dictionary entries: 36ms
The code for that looks like this:
public void Serialize(Dictionary<string, int> dictionary, Stream stream)
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(dictionary.Count);
foreach (var kvp in dictionary)
{
writer.Write(kvp.Key);
writer.Write(kvp.Value);
}
writer.Flush();
}
public Dictionary<string, int> Deserialize(Stream stream)
{
BinaryReader reader = new BinaryReader(stream);
int count = reader.ReadInt32();
var dictionary = new Dictionary<string,int>(count);
for (int n = 0; n < count; n++)
{
var key = reader.ReadString();
var value = reader.ReadInt32();
dictionary.Add(key, value);
}
return dictionary;
}
As others have said though, if you are concerned about users tampering with the file, encryption, rather than binary formatting is the way forward.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…