Comparison of several methods of string inversion and several methods of string Inversion
The following code is used first:
Class Program {static void Main (string [] args) {string str = "12345"; const int count = 10000; Stopwatch sw = Stopwatch. startNew (); for (int I = 0; I <count; I ++) {Reverse1 (str);} Console. writeLine ("Reverse1 time consumed: {0}", sw. elapsed); sw = Stopwatch. startNew (); for (int I = 0; I <count; I ++) {Reverse2 (str);} Console. writeLine ("Reverse2 time consumed: {0}", sw. elapsed); sw = Stopwatch. startNew (); for (int I = 0; I <count; I ++) {Reverse3 (str) ;}console. writeLine ("Reverse3 time consumed: {0}", sw. elapsed); Console. readLine ();} /// <summary> /// concatenate a string using string /// </summary> /// <param name = "str"> </param> /// <returns> </returns> private static string Reverse1 (string str) {string strReturn = ""; foreach (char c in str) {strReturn = c + strReturn;} return strReturn ;} /// <summary> /// concatenate a string using StringBuilder /// </Summary> /// <param name = "str"> </param> /// <returns> </returns> private static string Reverse2 (string str) {if (String. isNullOrEmpty (str) {throw new ArgumentNullException ("the string is empty! ");} StringBuilder sb = new StringBuilder (str. length); for (int I = str. length-1; I> = 0; I --) {sb. append (str [I]);} return sb. toString () ;}/// <summary> /// use the Array that comes with FCL. reverse () /// </summary> /// <param name = "str"> </param> /// <returns> </returns> private static string Reverse3 (string str) {var arr = str. toCharArray (); Array. reverse (arr); return new string (arr );}}
The current number of cycles is 10000. Comparison results
Obviously, the performance comparison of the three inversion algorithms is: Reverse1 <Reverse2 <Reverse3. we increase the number of cycles to 1000000.
According to the running results on my machine, the performance comparison result is still Reverse1 <Reverse2 <Reverse3. Let's briefly explain why such a result exists. In Reverse1 () and Reverse2 (), String concatenation is used to reverse the query. For String concatenation, StringBuilder is much better than String concatenation, this is mainly related to the immutability of string. If you use the reflector.exe tool to disassemble and view the FCL Array. reverse (), you will find that its code has been greatly optimized, and it does not use String concatenation to help Reverse the string. It uses an Array internally) returns the string reversal implemented by the position switch of the element.