Adam Machanic, Boston-based SQL Server developer, shares his experiences with programming, monitoring, and performance tuning SQL Server. And the occasional battle with the query optimizer.
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 <g>) 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!
Comment Notification
If you would like to receive an email when updates are made to this post, please register here
Subscribe to this post's comments using
About Adam Machanic
Adam Machanic is a Boston-based SQL Server developer, writer, and speaker. He focuses on large-scale data warehouse performance and development, and is author of the award-winning SQL Server monitoring stored procedure, sp_WhoIsActive. Adam has written for numerous web sites and magazines, including SQLblog, Simple Talk, Search SQL Server, SQL Server Professional, CoDe, and VSJ. He has also contributed to several books on SQL Server, including "SQL Server 2008 Internals" (Microsoft Press, 2009) and "Expert SQL Server 2005 Development" (Apress, 2007). Adam regularly speaks at conferences and training events on a variety of SQL Server topics. He is a Microsoft Most Valuable Professional (MVP) for SQL Server, a Microsoft Certified IT Professional (MCITP), and an alumnus of the INETA North American Speakers Bureau.