What does Array.Reverse() compile to?

arrays, c#, reverse

Solution

`Array.Reverse` is currently implemented in the .NET framework using a temporary array. You can find that out by using ILSpy. The compiler has no say in this. The method is implemented in a certain way, there is nothing the compiler changes here.

Whether or not this is the optimal solution depends on what you see as optimal, so you need to define that for yourself and then attach a profiler and verify it.

Problem

I would like to know what `Array.Reverse()` in C# would compile to and what kind of optimizations are made. My research has lead me down multiple paths a few notable ones being the XOR method like so: ``` Reverse(Array) { for(int i = 0, int len = Array.Length; i < Array.Length, i++ len--) { Array[i] ^= Array[len]; Array[len] ^= Array[i]; Array[i] ^= Array[len]; } } ``` Which I have found to be very capable of working with smaller arrays. As they get larger though the performance starts to degrade, however it seems to have the best memory applications due to the in memory nature of the reverse process. The second most notable way of reversing an array is to use a temporary array, Which I won't write out since it is pretty straight forward. But basically set the initial arrays first element to the last element of the temp array, and so on. This method tends to be the fastest method when memory is not an issue. So my question is this, does `Array.Reverse()` use a particular method? If not how does it determine which method to use? Which really comes down to whether or not I should trust the System libraries and the compiler to decide what is the fastest solution, and exactly how much I should trust that decision.

Original source