I've done a test.
For loop:
Code:
private static string ReverseString(string input)
{
string[] parts = input.Split(' ');
int j = parts.Length - 1;
for (int i = 0; i < j; i++, j--)
{
string tmp = parts[i];
parts[i] = parts[j];
parts[j] = tmp;
}
return string.Join(" ", parts);
}
vs.
Array.Reverse():
Code:
string[] parts = "one two three four five six".Split(' ');
Array.Reverse(parts);
string.Join(" ", parts);
When I did this test, the Array.Reverse() code was put directly within my benchmark method, and the ReverseString() function was called from the benchmarking method. The results:
Code:
(Benchmark Test... 10 averages of 1000000 runs)
# For loop method
> [Average 1/10] Complete - 3.180357 ticks
> [Average 2/10] Complete - 3.263104 ticks
> [Average 3/10] Complete - 3.305357 ticks
> [Average 4/10] Complete - 3.312106 ticks
> [Average 5/10] Complete - 3.349507 ticks
> [Average 6/10] Complete - 3.265488 ticks
> [Average 7/10] Complete - 3.300283 ticks
> [Average 8/10] Complete - 3.363832 ticks
> [Average 9/10] Complete - 3.29727 ticks
> [Average 10/10] Complete - 3.281331 ticks
# Result: 3.2918635 ticks
(Benchmark Test... 10 averages of 1000000 runs)
# Array.Reverse() Method
> [Average 1/10] Complete - 3.744852 ticks
> [Average 2/10] Complete - 3.829094 ticks
> [Average 3/10] Complete - 3.846189 ticks
> [Average 4/10] Complete - 3.828799 ticks
> [Average 5/10] Complete - 3.824417 ticks
> [Average 6/10] Complete - 3.801133 ticks
> [Average 7/10] Complete - 3.820336 ticks
> [Average 8/10] Complete - 3.813253 ticks
> [Average 9/10] Complete - 3.794533 ticks
> [Average 10/10] Complete - 3.818379 ticks
# Result: 3.8120985 ticks
I added the string.Join() just for making things consistent, I didn't care about using it's value, only calling the method to make things equal.
Understand that Array.Reverse() in the background is lots more complex than the function I wrote namely, ReverseString, taken the name from OP. However, we don't care about that, because by the method name itself, it is clear enough for what the method is supposed to do.
Perhaps even ReverseWords, would be more appropriate for this method name as well.