C# ASP.NET SQL SERVER

String Reverse in C#

 I had to write a string reverse function today and wasn't happy with my initial (basic) function so I posted it on Stack Overflow to see what other algorithms that developers might come up with. My restriction was that it had to be in C# 2.0 and so I couldn't use LINQ. Out of curiosity I decided to do a performance test on each of the functions and while I was at it I threw in the LINQ equivalent to see how it would perform. For the test of a 500 character string I looped each function 100,000 times and for the test of a 10 character string I looped the functions 10,000,000 times.

These are the functions that I tested:

// string concatenation with for loop
public string ReverseA(string text)
{
    char[] cArray = text.ToCharArray();
    string reverse = String.Empty;
    for (int i = cArray.Length - 1; i > -1; i--)
    {
        reverse += cArray[i];
    }
    return reverse;
}

// Array.Reverse function
public string ReverseB(string text)
{
    char[] charArray = text.ToCharArray();
    Array.Reverse(charArray);
    return new string(charArray);
}

// push/pop Stack<>
public string ReverseC(string text)
{
    Stack resultStack = new Stack();
    foreach (char c in text)
    {
        resultStack.Push(c);
    }

    StringBuilder sb = new StringBuilder();
    while (resultStack.Count > 0)
    {
        sb.Append(resultStack.Pop());
    }
    return sb.ToString();
}

// LINQ
public string ReverseD(string text)
{
    return new string(text.ToCharArray().Reverse().ToArray());
}

// StringBuilder
public string ReverseE(string text)
{
    char[] cArray = text.ToCharArray();
    StringBuilder reverse = new StringBuilder();
    for (int i = cArray.Length - 1; i > -1; i--)
    {
        reverse.Append(cArray[i]);
    }
    return reverse.ToString();
}

 Time Taken to Reverse a String

What surprised me was how poorley LINQ did on the short string compared to the others.

You may also find the rudimentary test harness that I put together interesting:

delegate string ReverseDelegate(string text);

public void RunPerformance()
{
    int loopCount = 10000000;
    int stringSize = 100;
    string[] reverseTextArray = Enumerable.Repeat("abcde", stringSize).ToArray();
    string reverseText = String.Join("", reverseTextArray);
    // reverseText = "1234567890";
    DateTime startTime, endTime;
    
    ReverseDelegate[] reverseFunc = new ReverseDelegate[5];
    reverseFunc[0] = ReverseA;
    reverseFunc[1] = ReverseB;
    reverseFunc[2] = ReverseC;
    reverseFunc[3] = ReverseD;
    reverseFunc[4] = ReverseE;

    AssertThatFunctionsWorkCorrectly(reverseFunc);

    TimeSpan[] reverseTime = new TimeSpan[reverseFunc.Length];

    for (int i = 0; i < reverseFunc.Length; i++)
    {
        startTime = DateTime.Now;
        for (int j = 0; j < loopCount; j++)
        {
            reverseFunc[i](reverseText);
        }
        endTime = DateTime.Now;
        reverseTime[i] = endTime - startTime;
        Console.WriteLine("{0}/{2} took {1}", i, reverseTime[i], reverseFunc[i].Method);
    }

    Console.WriteLine("break point");
}

private void AssertThatFunctionsWorkCorrectly(ReverseDelegate[] reverseFunc)
{
    string test = "abcdefghi";
    string expected = "ihgfedcba";
    for(int i=0; i

» Similar Posts

  1. Speed improvements with compiled regex
  2. MultiThread testing for speed
  3. Optimizing a custom Trim() function in C#

» Trackbacks & Pingbacks

    No trackbacks yet.
Trackback link for this post:
http://guyellisrocks.com/trackback.ashx?id=106

» Comments

  1. Bradley Grainger avatar

    I just posted a follow-up (to your blog and StackOverflow question) with a method that handles Unicode data correctly: code.logos.com/.../how_to_reverse_

    Bradley Grainger — October 23, 2008 12:12 AM
  2. guy ellis avatar

    Thanks Bradley!

    guy ellis — October 23, 2008 12:36 AM

» Leave a Comment