0

what is advantage of using MemoryMappedFile over BinaryFile?? Compared reading time of both the methods, time taken was almost same?

class Program
{
    public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
    {
        using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
        {
            var binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);
        }
    }

    public static void WriteObjectToMMF(string mmfFile, object objectData)
    {
        // Convert .NET object to byte array
        byte[] buffer = ObjectToByteArray(objectData);

        // Create a new memory mapped file
        using (MemoryMappedFile mmf =
               MemoryMappedFile.CreateFromFile(mmfFile, FileMode.Create, null, buffer.Length))
        {
            // Create a view accessor into the file to accommmodate binary data size
            using (MemoryMappedViewAccessor mmfWriter = mmf.CreateViewAccessor(0, buffer.Length))
            {
                // Write the data
                mmfWriter.WriteArray<byte>(0, buffer, 0, buffer.Length);
            }
        }
    }


}
Matthew Hudson
  • 1,306
  • 15
  • 36
anand
  • 307
  • 3
  • 14

1 Answers1

1

there is not much of a difference if you write sequentially to a file.

If you read or write with random access there is a huge difference however.

With memory mapped files only a (small) chunk of the data is actually mapped to memory.

DrKoch
  • 9,556
  • 2
  • 34
  • 43