posted on Monday, July 17, 2006 10:20 PM
by
amachanic
More on string reversal!
Cross-posted from SQLBlog! -
http://www.sqlblog.com
In the last installment,
I showed a potentially fastest method using Array.Reverse.After finding and fixing a bug in method #3 posted in my last installment (it is, in fact, quite a bit faster than method #1 when you don't have a big huge bug in the code ) creating a new method, and hearing from Mladenp
about a method he came up with, I decided that I should post another round of results. So, here are the five methods I'm now testing:
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(charArray[i]);
}
return sb.ToString();
}
public static string Reverse4(string s)
{
char[] charArray = s.ToCharArray();
int i = charArray.Length;
int j = i-1;
string[] outStr = new string[i];
while (i-- > 0)
{
outStr[j - i] = charArray[i].ToString();
}
return String.Join("", outStr);
}
public static string Reverse5(string s)
{
char[] charArray = s.ToCharArray();
int len = s.Length - 1;
for (int i = 0; i < len; i++, len--)
{
charArray[i] ^= charArray[len];
charArray[len] ^= charArray[i];
charArray[i] ^= charArray[len];
}
return new string(charArray);
}
Results (10000 iterations, 26-character string):
Reverse1: 106.767 ms
Reverse2: 12.752 ms
Reverse3: 61.902 ms
Reverse4: 87.963 ms
Reverse5: 12.15 ms
Winner, by a very small margin: Mladenp's XOR method!
Anyone else want to weigh in? Submissions are open!