String and stringbuilder personal summary, stringbuilder
StringAndStringBuilderIn-depth analysis
The starting point of this article is whether we really understand the use of stringbuilder during the development process, how to implement string operations (hash table), and whether stringbuilder sets the default capacity, when is stringbuilder used.
Concept 1StringAndStringbuliderUnderstanding
StringIt is one of the most commonly used types. It is a special reference type that is directly derived from an Object. Therefore, its values are stored on the managed stack. When constructing a new string, you do not need to use new. It is "immutable". After the string object is initialized, the length and content of the string object remain unchanged. You can think about how to change or add a string at this time?
StringBuliderBecause the string is "immutable", the performance will be lost when the string is modified multiple times ,. net to solve this problem, it provides a dynamic string creation method to overcome the performance loss caused by the immutable string. Compared with String, StringBuilder has fewer functions, including basic attributes and addition, deletion, and modification methods. But do you know that stringbuilder also has a fixed capacity value???,Note:StringBuliderCapacity(The default value is16)Although the StringBuilder object is a dynamic object that allows you to expand the number of characters in its encapsulated string, you can specify a value for the maximum number of characters it can accommodate. This value is called the capacity of the object and should not be confused with the string length of the current StringBuilder object. For example, you can create a new instance of the StringBuilder class with the string "Hello" (Length: 5) and specify the maximum capacity of this object to 25. When you modify StringBuilder, it does not re-allocate space for itself until the capacity is reached. When the capacity is reached, a new space is automatically allocated and the capacity is doubled. AvailableTo specifyStringBuilderClass capacity. The following code example specifies that the MyStringBuilder object can be expanded to a maximum of 25 white spaces. StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ", 25); in addition, you canRead/Write CapacityAttribute to set the maximum length of the object. The following code uses the Capacity attribute to define the maximum length of an object. MyStringBuilder. Capacity = 25; the EnsureCapacity method can be used to check the current Capacity of StringBuilder. If the capacity is greater than the passed value, no changes are made. However, if the capacity is smaller than the passed value, the current capacity is changed to match the passed value. You can also view or set the Length attribute. If you set the Length attribute to a value greater than the Capacity attribute, the Capacity attribute is automatically changed to the same value as the Length attribute. If you set the Length attribute to a value smaller than the string Length in the current StringBuilder object, the string is shortened.
IIWhy are changes affecting performance. (StringAndStringBuilder)
String:String s = "I am"; s + = "Sky"; how to allocate memory?
Note: If the re-allocation is true every time ,. net is certainly not so silly. At the very least, we should avoid having to allocate a new heap if the strings of the two strings are the same. Just make the same reference? Here is a term:String ReservedThe CLR creates a hash table during initialization. Every time a new string is created, it matches the hash table to check whether the same string exists. If yes, the existing old object is returned and referenced by the new variable. Otherwise, a copy of the string will be created and added to the hash table. The Key is the string, and the Value is the address of the string object on the stack.
Is it all like this? What are the special circumstances?
SummaryNewThe output object is not recorded in the hash table.
TringBuilderObjects maintain a buffer to accommodate the concatenation of new data. If there is enough space, new data will be appended to the end of the buffer; otherwise, a new and larger buffer will be allocated, and the data in the original buffer will be copied to the new buffer, then, append the new data to the new buffer.
Internal implementation principle
Summary:StringBuffer is a variable class and thread-safe string operation class. Any operation on the string to which it points will not produce new objects. Each StringBuffer object has a certain buffer capacity. When the string size does not exceed the capacity, no new capacity is allocated. When the string size exceeds the capacity, the capacity is automatically increased. The fact is that StringBuilder is faster than string because the intermediate object is generated during string concatenation and eventually garbage is generated. For example, string str = "a"; str + = "B"; str + = "c"; then, the final result is "abc ", but the second line produces "AB", which is just an intermediate object and garbage. Using StringBuilder will avoid the generation of such intermediate objects. What if I write this? String str = "a" + "B" + "c"; will this be slower than StringBuilder? No.
The generation of intermediate objects is the main cause of performance impact.
Iii. Test cases:
Private void button#click (object sender, EventArgs e)
{
Int number = int. Parse (textBox1.Text. ToString ());
GetStringTime (number );
GetStringBulider (number );
GetStringTime1 (number );
GetStringBulider1 (number );
}
/// <Summary>
/// Test string performance time
/// </Summary>
Private void GetStringTime (int number)
{
Stopwatch watch = new Stopwatch ();
List <String> li = new List <string> ();
Watch. Start ();
String str = "select * from testa inner join fast sorting time-consuming ";
For (int I = 0; I <number; I ++)
{
Li. Add (str );
}
Watch. Stop ();
Label1.Text = watch. ElapsedMilliseconds. ToString ();
}
Private void GetStringBulider (int number)
{
Stopwatch watch = new Stopwatch ();
List <String> li = new List <string> ();
Watch. Start ();
StringBuilder strb = new StringBuilder ();
Strb. Append ("select * from testa inner join dsadfasfsadfa fast sorting time-consuming ");
For (int I = 0; I <number; I ++)
{
Li. Add (strb. ToString ());
}
Watch. Stop ();
Label2.Text = watch. ElapsedMilliseconds. ToString ();
}
/// <Summary>
/// Test string performance time changes
/// </Summary>
Private void GetStringTime1 (int number)
{
Stopwatch watch = new Stopwatch ();
List <String> li = new List <string> ();
Watch. Start ();
String str = "select * from testa inner join fast sorting time-consuming ";
For (int I = 0; I <number; I ++)
{
Str = str + "select * from testa inner join fast sorting time-consuming ";
}
Watch. Stop ();
Label1.Text = label1.Text + "unchanged, changed" + watch. ElapsedMilliseconds. ToString ();
}
/// <Summary>
/// Test the performance of stringBulider changes
/// </Summary>
/// <Param name = "number"> </param>
Private void GetStringBulider1 (int number)
{
Stopwatch watch = new Stopwatch ();
List <String> li = new List <string> ();
Watch. Start ();
StringBuilder strb = new StringBuilder ();
Strb. Append ("select * from testa inner join dsadfasfsadfa fast sorting time-consuming ");
For (int I = 0; I <number; I ++)
{
Strb. Append ("select * from testa inner join dsadfasfsadfa fast sorting time-consuming ");
}
Watch. Stop ();
Label2.Text = label2.Text + "unchanged, changed" + watch. ElapsedMilliseconds. ToString ();
}
As follows:
Note: The first line of each graph indicates string, the second line indicates stringbulider, and the change indicates the meaning of str ++ or append.
Iv. Summary:StringAndStringbulider.
1. Sting is constant, and people in the string department can change.
2. For simple string connection operations, stringbuilder is not always better than string in terms of performance. Because the creation of stringbulider objects also consumes a lot of performance, the excessive abuse of stringbuilder will result in a waste of performance rather than savings in the case of few string connections, the use of stringbuilder is considered only for a large number of unpredictable string operations. From the final analysis, we can see that there is no big difference within 100 rows.
3. For the use of Stringbulider, it is best to set an appropriate capacity value. Otherwise, it is better to perform frequent memory allocation operations if the default capacity is insufficient.
You can think deeply. First, have we processed the appropriate capacity value? Second, do we repeatedly use stringbuilder to explain that the performance is good, but are there any character operations in the 100 rows.
A simple string connection operation can properly consider the use of string. Concat and string. join. (String. concat packing operation ).
References:
Http://www.cnblogs.com/juqiang/archive/2005/04/19/140538.html.
Http://www.cnblogs.com/huangxincheng/p/4042105.html.
Http://www.cnblogs.com/heartstill/archive/2011/11/11/2245411.html.
Http://www.cnblogs.com/kid-li/archive/2006/10/18/532174.html.
Http://www.cnblogs.com/gfwei/archive/2007/03/14/674499.html.
Http://www.cnblogs.com/skychen1218/p/3594258.html.
Books: What you must know. netWhat isString(345Page).