'What is the fastest way to reverse a byte array in c#?

I'm working on a project that needs to be very fast so I am asking this question: What is the fastest way to reverse a byte array in c#? (including unsafe code)



Solution 1:[1]

In-place? Probably something like this:

byte[] Reverse( byte[] b )
{
  for ( int i = 0 , int j = b.Length-1 ; i < j ; ++i, --j )
  {
    arr[i] ^= arr[j] ;
    arr[j] ^= arr[i] ;
    arr[i] ^= arr[j] ;
  }
  return b;
}

Idempotent, where you allocate a new array to contain the reversed octets, probably something like this:

byte[] Reverse( byte[] b )
{
  byte[] r = new byte[b.Length];
  for ( int i = 0, int j = b.Length ; i < b.Length ; )
  {
    r[i++] = b[--j];
  }
  return r;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicholas Carey