Funny problem: How fast can you reverse a string in Java and C#?

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.

These 2 approaches are all right, and we can reverse an alphabet string and also, we can reverse an Unicode string like “私は中国人です。”. But if we need to reverse 10,000 strings and each string was 10,000 characters long, which one could be faster?

 

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:

  1. Using XOR to swap string character is not a good idea.
  2. 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().

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>