The most efficient way to write binary data to a file in C #

I am trying to optimize a class that serializes objects in binary format and writes them to a file. I am currently using FileStream (in sync mode due to the size of my objects) and BinaryWriter. This is 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(); } } 

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

+4
source share
1 answer

Yes - you can use a different serialization format. The built-in serialization format is rich, but it also has drawbacks - it is quite verbose compared to some other custom formats.

The format I'm most familiar with is Protocol Buffers , which is Google's efficient and portable binary format. However, it does require that you design the types you want to serialize differently. There are always pros and cons :)

There are other binary serialization formats, such as Thrift .

You might want to stick with the built-in serialization, but you should know that other options are available.

Before you go too far, you need to determine what you need and how much you really need to worry about performance anyway. You can spend a lot of time exploring options when what you have might be ok :)

+5
source

All Articles