A personal summary of string and StringBuilder

Source: Internet
Author: User

String and the StringBuilder in-depth analysis

Preface: The starting point of this paper is whether we develop a real understanding of the use of StringBuilder, string string operation is how to implement (hash table), StringBuilder whether to set the default value of capacity, when the StringBuilder.

a concept String and the Stringbulider the Understanding

string is one of the most common types we use, and is a special reference type that derives directly from object, so its value is stored on the managed heap. 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 are determined to be constant. Can think about this time, we need to change or add a string, what kind of action?

StringbuliderBecause of the "immutable" string, which results in a loss of performance when the string is modified multiple times,. NET to solve this problem, a method of dynamically creating a string is provided to overcome the performance loss caused by the string immutable. StringBuilder and string, less function, only the basic properties and additions and deletions of the method. But do you know that StringBuilder also has a fixed capacity value??? Note:Stringbulidercapacity  (the default is -)Although the StringBuilder object is a dynamic object, it allows you to expand the number of characters in the string it encapsulates, but you can specify a value for the maximum number of characters it can hold. This value is called the capacity of the object and should not be confused with the length of the string that the current StringBuilder object holds. For example, you can create a new instance of the StringBuilder class with the string "Hello" (length 5), and you can specify that the object has a maximum capacity of 25. When StringBuilder is modified, it does not redistribute space for itself until the capacity is reached. When the capacity is reached, new space is automatically allocated and the capacity doubles. can useone of the overloaded constructors to specifyStringBuilderThe capacity of the class. The following code example specifies that the Mystringbuilder object can be expanded to a maximum of 25 blanks.   StringBuilder Mystringbuilder = new StringBuilder ("Hello world!", 25); Alternatively, you canUse Read/Write Capacityproperty to set the maximum length of the object。  The following code example uses the capacity property to define the maximum length of an object.   Mystringbuilder.capacity = 25; The Ensurecapacity method can be used to check the capacity of the current StringBuilder. If the capacity is greater than the value passed, no changes are made, but if the capacity is less than the value passed, the current capacity is changed so that it matches the value passed. You can also view or set the Length property. If the length property is set to a value greater than the capacity property, the capacity property is automatically changed to the same value as the Length property. If you set the Length property to a value that is less than the length of the string within the current StringBuilder object, the string is shortened.

two and why the change affects performance. (string and StringBuilder)

string:string s = "I am"; s + = "Sky"; How to allocate memory?

Note: If it's crazy to redistribute this every time,. NET is certainly not that silly, at least to avoid if the two string strings identical, I do not need to allocate a new heap, only need to make the same reference is good? Here is a noun: string retention , CLR initialization will create a hash table, each build a new string will match the hash table, find whether there is the same string, if the match, will return the existing old object, the new variable to be referenced. Otherwise, a copy of the string is created to be added to the hash table, and key is the string, and value is the address of the string object on the heap.

Is it all the same, is there any special situation?

Summary New the objects that come out are not recorded in the hash table.

The Tringbuilder object maintains a buffer to accommodate the concatenation of new data. If there is enough space, the new data is appended to the end of the buffer, otherwise a new, larger buffer is allocated, the data in the original buffer is copied to the new buffer, and the new data is appended to the new buffer.

Internal implementation principle

Summary: StringBuffer is a variable class, and thread-safe string manipulation class, and any manipulation of the string it points to does not produce new objects. Each StringBuffer object has a certain buffer capacity, and when the string size does not exceed the capacity, no new capacity is allocated and the capacity is automatically increased when the string size exceeds the capacity. The fact is that StringBuilder is faster than string because it produces an intermediate object in the concatenation of strings, and ultimately garbage. such as: string str = "a"; str + = "B"; str + = "C"; then the end result is "ABC", but the second line produces "AB" just an intermediate object, which is a garbage. Using StringBuilder will avoid the creation of this intermediate object. What if I write this? String str = "a" + "B" + "C"; Is this slower than StringBuilder? No.

The production of intermediate objects is the main factor that affects performance.

Three, the test case:

private void Button1_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 quick sort time consuming quick sequencing 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 Quick Sort time consuming quick sequencing time consuming");

for (int i = 0; i < number; i++)

{

Li. ADD (STRB. ToString ());

}

Watch. Stop ();

Label2. Text = watch. Elapsedmilliseconds.tostring ();

}

<summary>

Testing 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 quick sort time consuming quick sequencing time consuming";

for (int i = 0; i < number; i++)

{

str = str+ "SELECT * from testa inner join quick sort time consuming fast sequencing time consuming";

}

Watch. Stop ();

Label1. Text =label1. text+ "Unchanged, change" + 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 Quick Sort time consuming quick sequencing time consuming");

for (int i = 0; i < number; i++)

{

Strb. Append ("SELECT * from testa inner join DSADFASFSADFA Quick Sort time consuming quick sequencing time consuming");

}

Watch. Stop ();

Label2. Text =label2. text+ "Unchanged, change" + watch. Elapsedmilliseconds.tostring ();

}

As follows:

Note: The first row of each figure represents a string, the second line represents Stringbulider, and the change represents the meaning of str++ or append.

Four: summary: String and the Stringbulider overall summary of the.

1. The sting is constant, and the people in the string section are changeable.

2. For a simple string connection operation, StringBuilder on performance is not always better than string. Because Stringbulider object creation also consumes a lot of performance, in the case of less string connection, excessive misuse of StringBuilder can lead to wasted performance rather than savings, only a large number of unpredictable string operations to consider the use of StringBuilder. From the final analysis, it can be seen that if it is within 100 lines there is no significant difference.

3. The use of Stringbulider, it is best to establish a suitable capacity value, or better than the default capacity is not enough and frequent memory allocation operations, is inappropriate implementation method.

Can ponder, the first we to the appropriate capacity value to deal with it? Second, do we use StringBuilder to say that performance is good, but is there a difference in the character operation within 100 rows?

A simple string connection operation can consider the string in moderation. Use of Concat and String.Join. (String.Concat boxing operation).

Reference article:

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/3593678.html.

Book: "What You must know. NET" what is a string(345 page).

A personal summary of string and StringBuilder

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.