Search code examples
c#multithreadingbinary-serialization

binary file generation performance


I'have about 30 000 object to binary serialize in a file, I'm using with a simple foreach loop this basic code to do that :

FileStream fileStream = new FileStream(pathToFile, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize((Stream) fileStream, objectToSerialize);
fileStream.Close();

can I accelerate the processus using multithreading or another way? (memory stream etc)


Solution

  • Reuse the binaryFormatter instead of recreating it each time. Using a BufferedStream between the FileStream and the formatter may also improve performance. BTW: Use "Using" to ensure that your file streams are closed, even in case of an exception being raised when serializing.