title: De / Interleave array fast in C#
body: <p>I am looking for the fastest way to de/interleave a buffer.
  To be more specific, I am dealing with audio data, so I am trying to optimize the time I spend on splitting/combining channels and FFT buffers.</p>
  
  <p>Currently I am using a for loop with 2 index variables for each array, so only plus operations, but all the managed array checks will not compare to a C pointer method.</p>
  
  <p>I like the Buffer.BlockCopy and Array.Copy methods, which cut a lot of time when I process channels, but there is no way for an array to have a custom indexer.</p>
  
  <p>I was trying to find a way to make an array mask, where it would be a fake array with a custom indexer, but that proves to be two times slower when using it in my FFT operation. I guess there are a lot of optimization tricks the compiler can pull when accessing an array directly, but accessing through a class indexer cannot be optimized.</p>
  
  <p>I do not want an unsafe solution, although from the looks of it, that might be the only way to optimize this type of operation.</p>
  
  <p>Thanks.</p>
  
  <p>Here is the type of thing I'm doing right now:</p>
  
  <pre><code>private float[][] DeInterleave(float[] buffer, int channels)
  {
      float[][] tempbuf = new float[channels][];
      int length = buffer.Length / channels;
      for (int c = 0; c &lt; channels; c++)
      {
          tempbuf[c] = new float[length];
          for (int i = 0, offset = c; i &lt; tempbuf[c].Length; i++, offset += channels)
              tempbuf[c][i] = buffer[offset];
      }
      return tempbuf;
  }
  </code></pre>