views:

177

answers:

1

Hi,

I am trying to optimize a class that serializes objects in binary format and writes them in a file. I am currently using a FileStream (in sync mode because of the size of my objects) and a BinaryWriter. Here's what my class looks like:

public class MyClass
{
    private readonly BinaryWriter m_binaryWriter;
    private readonly Stream m_stream;

    public MyClass()
    {
        // Leave FileStream in synchronous mode for performance issue (faster in sync mode)
        FileStream fileStream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite, maxSize, false);
        m_stream = fileStream;

        m_binaryWriter = new BinaryWriter(m_stream);
    }

    public void SerializeObject(IMySerializableObject serializableObject)
    {
        serializableObject.Serialize(m_binaryWriter);
        m_stream.Flush();
    }
}

A profiler run on this code shows good performance but I was wondering if there are other objects (or techniques) that I could use to improve the performance of this class.

+5  A: 

Yes - you could use a different serialization format. The built-in serialization format is rich, but has downsides too - it's quite verbose compared with some other custom formats.

The format I'm most familiar with is Protocol Buffers, which is an efficient and portable binary format from Google. It does, however, require you to design the types that you want to serialize in a different way. There are always pros and cons :)

There are other binary serialization formats too, such as Thrift.

You may want to stick to the built-in serialization, but it's worth knowing that other options are available.

Before you go too far, however, you should determine what you care about and how much you actually need to worry about the performance anyway. You could waste a lot of time investigating options when what you've got may be fine as it is :)

Jon Skeet
"You *may* want to stick to the built-in serialization": just for completeness - my constant argument about the built-in binary serializer (`BinaryFormatter`) is about *brittleness*, in particular versioning and implementation details. It does, however, have the convenience of being the simplest to get working.
Marc Gravell
"It does, however, require you to design the types that you want to serialize in a different way." - it depends on which implementation you use... ;-p
Marc Gravell