title: Performance issue when serializing multi-dimensional arrays using BinaryFormatter in .NET
body: <p>I'm using the <code>BinaryFormatter</code> to serialize a fairly simple multi-dimentional array of floats, although I suspect that the problem occurs with any primitive types.  My multi-dimensional array contains 10000x16 floats (160k) and serializing on my PC runs at ~8 MB/s (60 second benchmark writing ~500 MB to SSD drive).  Code:</p>
  
  <pre><code>        Stopwatch stopwatch = new Stopwatch();
  
          float[,] data = new float[10000 , 16];  // Two-dimensional array of 160,000 floats.
          // OR
          float[]  data = new float[10000 * 16];  // One-dimensional array of 160,000 floats.
  
          var formatter = new BinaryFormatter();
          var stream = new FileStream("C:\\Temp\\test_serialization.data", FileMode.Create, FileAccess.Write);
  
          // Serialize to disk the array 1000 times.
          stopwatch.Reset();
          stopwatch.Start();
          for (int i = 0; i &lt; 1000; i++)
          {
              formatter.Serialize(stream, data);
          }
          stream.Close();
          stopwatch.Stop();
  
          TimeSpan ts = stopwatch.Elapsed;
  
          // Format and display the TimeSpan value.
          string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:000}",
              ts.Hours, ts.Minutes, ts.Seconds,
              ts.Milliseconds);
          Console.WriteLine("Runtime " + elapsedTime);
          var info = new FileInfo(stream.Name);
          Console.WriteLine("Speed: {0:0.00} MB/s", info.Length / ts.TotalSeconds / 1024.0 / 1024.0);
  </code></pre>
  
  <p>Doing the same thing but using a one-dimensional array of 160k floats, the same amount of data is serialized to disk at ~179 MB/s.  Over 20x faster!  <strong>Why does serializing a two-dimensional array using <code>BinaryFormatter</code> perform so poorly?</strong>  The underlying storage of the of the two arrays in memory should be identical. (I've done unsafe native pin_ptr and copying to and from 2D arrays in C++/CLI).  </p>
  
  <p>A hackish solution would be to implement <code>ISerializable</code> and do a memcopy (unsafe/ptr pinning/block memcopy) the 2D array into a 1D array and serialize that and the dimensions.  Another option I am considering is a switch to <code>protobuf-net</code>.</p>