1. Differences between string and stringbuilder.
The string object is unchangeable.The length or any character in it cannot be changed.
String @ String = " A " ;
@ String = @ String + " B " ;
AboveCodeIt is mistaken that @ string can increase the length. In fact, the second code re-creates a new object, and the first object is discarded, which will become the object collected by the garbage collector.
C # cannot use new string () to construct a String object. If possible, the above Code is equivalent:
String @ String = New String ( " A " );
@ String = New String ( " A " + " B " );
Stringbuilder is variable.It is a class used to perform dynamic operations on strings and characters.
Implemented Using stringbuilder:
Stringbuilder = New Stringbuilder ( " A " );
Stringbuilder. append ( " B " );
Stringbuilder has an internal character array that is long enough to store string objects. When the string length does not exceed the character array length, all operations are performed on the same character array. When the length exceeds, stringbuilder automatically creates a longer array and copies the original data to the new array.
2. Comparison of string operation performance.
Let string and stringbuilder perform the same operation: append a string "A" cyclically ".
Public Static Void Comparestring ()
... {
Usestring ();
Usestringbuilder ();
}
Private Static Void Usestring ()
... {
String @ String = "" ;
Datetime starttime = Datetime. now;
For ( Int I = 0 ; I < 10000 ; I ++ )
... {
@ String+ = "A";
}
Datetime endtime = Datetime. now;
Timespan = Endtime - Starttime;
Console. writeline (timespan. tostring ());
}
Private Static Void Usestringbuilder ()
... {
Stringbuilder = New Stringbuilder ();
Datetime starttime = Datetime. now;
For ( Int I = 0 ; I < 1000000 ; I ++ )
... {
Stringbuilder. append ("A");
}
Datetime endtime = Datetime. now;
Timespan = Endtime - Starttime;
Console. writeline (timespan. tostring ());
}
Run the comparestring () function to obtain the following results:
|
Running Times |
Time |
String |
10 thousand times |
0.078125 seconds |
Stringbuilder |
1 million times |
0.046875 seconds |
Conclusion: The dynamic append speed of string using stringbuilder is about 200 times that of string.
Supplement: for different string lengths and different operations, such as remove, the performance varies. One test is required.
From: http://blog.csdn.net/xiaomin98/archive/2008/01/15/2045002.aspx