I saw an interview question.
Write a function to reverse a string.
It’s a simple question, Hmm? But not so simple.
In Java, StringBuilder class provided a convenient method to reverse the characters it holds, and in C#, we have a static method Array.reverse() to help us. Also, we can write it by ourselves(it’s not a big deal, right?).
OK, let’s take a look at how we can do this.
It’s simple. Hmm? We turn the string into char array, and swap the array element. It’s done.
If we use the API provided by .NET Framework, it will be much more simple.
Here is the output generated by the above program.
The XOR is based on the fasted int value swap. This algorithm won’t need the temporary variable. And if we treat all the string data as bit data, this method works fine for string. Even when dealing with Unicode characters. But it cost much more time than the API do. In most cases, it cost 10 times longer than Array.reverse() do.
Before we draw the conclusion, let’s take a look at Java can do.
Java doesn’t have a similar Array.reverse() function, but it does provide a StringBuilder.reverse() method. Let’s take a look at what Java can do.
Here is the output generated on my desktop.
So far, we can have several conclusions:
- Using XOR to swap string character is not a good idea.
- Array.Reverse() provided by .NET framework performs much faster than any other methods, but WHY?
The reason Array.Reverse() has a good performance is here:
BTW .. I just had a look at the implementation of Array.Reverse, and its done natively for chars … it should be much faster than the StringBuilder option. – Sam Saffron Oct 23 ‘08 at 0:46
Ouch, remember, if you want to use .NET to perform an array reverse, please use Array.Reverse().














