原文:c#字串三種逆轉方法及效能比較
看到後覺得很奇怪,個人認為在很多情況下類庫方法肯定要比自己寫的方法效能好
原文作者傳入的字串,如果是傳入字元數組的話測試結果則大大出乎作者的意外。
修改代碼如下:
class StringReverse { /// <summary> /// 字串逆轉-StringBuilder實現 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ReverseUsingStringBuilder(char[] str) { int length = str.Length; StringBuilder sb = new StringBuilder(length); for (int i = length - 1; i >= 0; i--) { sb.Append(str[i]); } return sb.ToString(); } /// <summary> /// 字串逆轉-CharArray實現 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ReverseUsingCharArray(char[] str) { char[] arr = str; Array.Reverse(arr); return new string(arr); // return string.Join(string.Empty,str.Reverse()); } /// <summary> /// 字串逆轉-異或實現 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ReverseUsingXor(char[] str) { char[] arr = str; int l = arr.Length-1; //交換值 for (int i = 0; i < l; i++, l--) { str[i] ^= str[l]; str[l] ^= str[i]; str[i] ^= str[l]; } return new string(str); } public delegate string funcDelegate(char[] s); /// <summary> /// 測試方法 /// </summary> /// <param name="description">方法描述</param> /// <param name="func">測試方法</param> /// <param name="times">執行次數</param> /// <param name="str">測試字串</param> public static void Benchmark(string description, funcDelegate func, int times, char[] str) { Stopwatch sw = new Stopwatch(); sw.Start(); for (int j = 0; j < times; j++) { func(str); } sw.Stop(); Console.WriteLine("方法{0}:調用{1}次,用時{2}.", description, times, sw.ElapsedTicks); } /// <summary> /// 產生指定長度隨機字串 /// </summary> /// <param name="length">字條串長度</param> /// <returns></returns> public static char[] RandomString(int length) { Random random = new Random(); // StringBuilder sb = new StringBuilder(); char[] sb=new char[length]; for (int i = 0; i < length; i++) { sb[i]=Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))); } return sb; } static void Main(string[] args) { int[] lengths = new int[] { 1, 10, 15, 25, 50, 75, 100, 1000, 100000 }; // int[] lengths = new int[] { 1, 10, 15, 25, 50, 75, 100}; foreach (int len in lengths) { //每個方法都執行10000次,力求精確 int iterations = 10000; //產生隨機測試字串 char[] testString = StringReverse.RandomString(len); //列印測試資訊 StringReverse.Benchmark(String.Format("String Builder (測試字串長度為{0})", len), StringReverse.ReverseUsingStringBuilder, iterations, testString); StringReverse.Benchmark(String.Format("Array.Reverse (測試字串長度為{0})", len), StringReverse.ReverseUsingCharArray, iterations, testString); StringReverse.Benchmark(String.Format("Xor (測試字串長度為{0})", len), StringReverse.ReverseUsingXor, iterations, testString); Console.WriteLine(); } Console.Read(); } }
測試結果: