Saving a Dictionary in C# - Serialization?

后端 未结 6 1713
逝去的感伤
逝去的感伤 2020-12-13 08:09

I am writing a C# application that needs to read about 130,000 (String, Int32) pairs at startup to a Dictionary. The pairs are stored in a .txt file, and are thus easily mod

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 08:36

    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 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 Deserialize(Stream stream)
    {
        BinaryReader reader = new BinaryReader(stream);
        int count = reader.ReadInt32();
        var dictionary = new Dictionary(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.

提交回复
热议问题