Shea Levy
Shea Levy

Reputation: 5435

Quickest C# Serializer

I need to serialize an OrderedDictionary, and I need it fast. I don't care about security or human-readability, I just need the fastest way to write the OrderedDictionary to file and read it back in again, so long as the serialization is consistent (same set of key-value pairs, same file contents). Is BinaryFormatter the best choice?

Upvotes: 3

Views: 749

Answers (3)

Kevin Hsu
Kevin Hsu

Reputation: 1756

If you're looking for the fastest way, extra coding not being a problem, you could try this:

Serialize: 1. Write your dictionary data to an in-memory byte array. Assuming your dictionary isn't too huge, this should be relatively cheap, time-wise. 2. Write a small header containing the #records, and then write the array to file.

Deserialize: 1. Read the # items and instantiate your OrderedDictionary with that as the capacity. 2. Read the data back into an array, instantiate each object, and write back to the OrderedDictionary.

I think this won't be hugely faster than more traditional methods, but maybe worth a try if you're trying to eek out every last bit of performance.

A faster way would be to write your own IOrderedDictionary with intimate knowledge of your objects, and have it store them in a way optimized for fast serialization (e.g. a flat buffer that can be slammed to disk quickly). Perhaps even faster would be to use some indexing file format (maybe SQLite?) and write a caching IOrderedDictionary adapter to it. This would let you amortize the deserialization cost.

Upvotes: 0

David Schmitt
David Schmitt

Reputation: 59375

You might look into protobuf, Google's serialization format. There are several implementations for C#:

There is a performance comparison online.

Upvotes: 5

Will Dean
Will Dean

Reputation: 39530

BinaryFormatter is almost certainly the fastest of the built-in serializers, but it wouldn't be very hard to measure the alternatives and check.

Upvotes: 4

Related Questions