Search code examples
c#.netbinarywriter

Efficiently writing an int array to file


I have a potentially larger int array that I'm writing to a file using BinaryWriter. Of course, I can use the default approach.

using (BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create)))
{
    writer.Write(myIntArray.Length);
    foreach (int value in myIntArray)
        writer.Write(value);
}

But this seems horribly inefficient. I'm pretty sure an int array stores data contiguously in memory. Is there no way to just write the memory directly to a file like you can with a byte array? Maybe a way to cast (not copy) the int array to a byte array?


Solution

  • There is support for the most efficient form without any copying in .NET Core via MemoryMarshal.Cast and Span<T>. This directly reinterprets the memory but this is potentially nonportable across platforms so it should be used with care:

     int[] values = { 1, 2, 3 };
    
     using (var writer = new BinaryWriter(File.Open(path, FileMode.Create)))
     {
         Span<byte> bytes = MemoryMarshal.Cast<int, byte>(values.AsSpan());
         writer.Write(bytes);
     }
    

    Some relevant discussion of this API when it was moved from MemoryExtensions.NonPortableCast

    However I will say your original is actually going to be fairly efficient because both BinaryWriter and FileStream have their own internal buffers that are used when writing ints like that.