Home Uncategorized Reversing a string in .NET

    Reversing a string in .NET

    78
    0

    Over in the Simple-Talk forums, there is a good thread going about how best to reverse a string in .NET, since no string reverse method is included in the BCL.

    A few suggestions were made, and someone implied that they were too complex and that simplicity is the most important factor.  Personally, I wonder — does complexity really matter in this case?  I would expect that you’d program this kind of thing exactly once, put it into a utility class somewhere, and never worry about the implementation again.  Given that assumption, it becomes more of a performance question for me.

    To that end, I’ve run a few tests.  I created three methods — the first is a method using StringBuilder, as suggested by one of the respondants in the thread who felt it was the simplest method of achieving tho goal.  The second uses Array.Reverse, and is perhaps slightly more obscure.  The third method is a modification of the first, in which the main loop iterates over an array of chars instead of the string, which I had a hunch would be faster (alas, tests show that I was not correct in my assumption).  Following are the methods:

    [sql] public static string Reverse1(string s)
    {
    StringBuilder sb = new System.Text.StringBuilder(s.Length);
    int i = s.Length;

    while (i– > 0)
    {
    sb.Append(s[i]);
    }

    return sb.ToString();
    }

    public static string Reverse2(string s)
    {
    char[] rev = s.ToCharArray();
    Array.Reverse(rev);
    return (new string(rev));
    }

    public static string Reverse3(string s)
    {
    char[] charArray = s.ToCharArray();

    int i = charArray.Length;

    StringBuilder sb = new System.Text.StringBuilder(i);

    while (i– > 0)
    {
    sb.Append(s[i]);
    }

    return sb.ToString();
    }

    [/sql] I turned on Visual Studio’s profiler to collect timings and ran these methods in a loop.  First test was reversing 26 characters (a-z), which I ran in a loop 10,000 times for each method.  Results:

    [sql]Reverse1: 506.775 ms
    Reverse2: 58.327 ms
    Reverse3: 522.484 ms
    [/sql] The second test was reversing 2080 characters (a-z repeated 80 times).  I was only able to run this test in the loop 2500 times, as my workstation is currently very low on disk space and the VS profiler’s output takes up a lot of room.  Results:

    [sql]Reverse1: 2060.424 ms
    Reverse2: 117.874 ms
    Reverse3: 2368.861 ms
    [/sql] Results are total time spent in each function and its children over the course of all iterations.

    So for me, the Array.Reverse method is what I would use… Anyone out there have a better version to share?

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here