C #’s string and StringBuilder


1. When to use string? When to use StringBuilder?

Once a string is created, its size cannot be modified. Each time one of the methods in the system.string class is used, a new string object must be created in memory, which requires allocating new space for the new object. The overhead associated with creating a new string object can be very expensive in cases where repeated modifications to the string are required. If you want to modify the string without creating a new object, you can use the system.text.stringbuilder class. For example, using the StringBuilder class can improve performance when many strings are connected together in a loop.

Therefore, if you do not add or delete strings frequently, you do not need StringBuilder when accumulating several fixed strings. After all, the initialization of StringBuilder also takes time. If you add or delete strings frequently, use StringBuilder.

String a1 = "abc"; // allocate a fixed memory size
a1+="def"; // create a new memory allocation A1, which is expensive

StringBuilder sb = new StringBuilder(20); // specify the allocation size
sb.Append('abc'); // allocate to heap
sb.Append('def'); // it will not be destroyed, but will be appended directly.

Summary: the output results of A1 and Sb above are the same. But there is a big difference in memory allocation.

2. Difference between string and StringBuilder

After the string is declared, the size in memory cannot be modified, and StringBuilder can freely expand the size (string is allocated in the stack area and StringBuilder is allocated in the heap area)

1)String(Detailed explanation of c# string string)

String s1 = new String(new char[] { 'c', 'h', 'i', 'n', 'a' });
String s2 = "abc";


StringBuilder sb = new StringBuilder(5); // When the allocation size is specified, performance is improved. It does not reallocate space for itself until it reaches capacity. If the specified size is exceeded, the system will double the current size, that is, 10,15,20. It is recommended that you specify a size
sb.Capacity = 25; // In addition, you can use the read / write capacity property to set the maximum length of the object.

//The ensurecapacity method can be used to check the capacity of the current StringBuilder. If the capacity is greater than the transmitted value, no change is made; However, if the capacity is less than the passed value, the current capacity is changed to match the passed value.   
//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. Setting the length property to a value less than the length of the string within the current StringBuilder object shortens the string.   

//Five methods to modify the contents of StringBuilder
StringBuilder. Append // append information to the end of the current StringBuilder.     
StringBuilder. Appendformat // replace the format specifier passed in the string with formatted text.     
StringBuilder. Insert // inserts a string or object into the specified index of the current StringBuilder object.     
StringBuilder. Remove // removes the specified number of characters from the current StringBuilder object.     
StringBuilder. Replace // replaces the specified character at the specified index.

//The append method can be used to add the string representation of text or object to the end of the string represented by the current StringBuilder object.
//The following example initializes a StringBuilder object to "Hello world" and appends some text to the end of the object. Space will be allocated automatically as needed. 
StringBuilder sb = new StringBuilder("Hello World!");  
sb.Append(" What a beautiful day.");  
Console.WriteLine(sb); // Result: Hello world! What a beautiful day. 

//The appendformat method adds text to the end of StringBuilder and implements the IFormattable interface, so it can accept the standard format string described in the formatting section. You can use this method to customize the format of variables and append these values to StringBuilder.
//The following example uses the appendformat method to place an integer value formatted as a monetary value at the end of StringBuilder.  
int MyInt = 25;    
StringBuilder sb = new StringBuilder("Your total is ");  
sb.AppendFormat("{0:C}   ",   MyInt);  
Console.WriteLine(sb); // Result: your total is $25.00   

//The insert method adds a string or object to the specified location in the current StringBuilder.
//The following example uses this method to insert a word into the sixth position of StringBuilder.
StringBuilder sb = new StringBuilder("Hello World!");  
sb.Insert(6,"Beautiful ");  
Console.WriteLine(sb); // Result: Hello beautiful world!  

//The remove method removes the specified number of characters from the current StringBuilder. The removal process starts at the specified zero based index.
//The following example uses the remove method to shorten StringBuilder.   
StringBuilder sb = new StringBuilder("Hello World!");  
Console.WriteLine(sb); // Result: Hello

//Using the replace method, you can replace a character in a StringBuilder object with another specified character.
//The following example uses the replace method to search the StringBuilder object, find all exclamation point characters (!), and replace them with the question mark character (?).
StringBuilder sb = new StringBuilder("Hello World!");  
sb.Replace('!',   '?');  
Console.WriteLine(sb); // Result: Hello World?

Let’s take a look at how memory is allocated as follows:


3) After knowing how they are allocated, you can distinguish “= =”, “equals” and “object. Referenceequals (obj1, obj2)”.

(1) Before this = =, let’s talk about it: maybe Java programmers will feel a little confused when they see here. In Java, string type is put in the heap. C # is different. Microsoft optimizes the string type

(2) Microsoft uses it when processing stringsHash table:What is it? The simple understanding is that when you create the string “China”, when you re create the string, the compiler will not open up new memory for storage. It points directly to the first created address.

(3) See the following code:

string s1 = "china";
string s2 = "china";
String s3 = new String(new char[] { 'c', 'h', 'i', 'n', 'a' });
String s4 = new String(new char[] { 'c', 'h', 'i', 'n', 'a' });
Console.WriteLine(s1 == s2);    //True 
Console.WriteLine(s1.Equals(s2));   //True
Console.WriteLine(Object.ReferenceEquals(s1, s2));  //True
Console.WriteLine(s3 == s4);    // True Microsoft optimizes it, string S1 = new string (New char [] {C ',' H ',' I ',' n ',' a '}); Equivalent to string S1 = "China"; So S1 = = S3 above is true.
Console.WriteLine(s3.Equals(s4));   //True
Console.WriteLine(Object.ReferenceEquals(s3, s4));  //False
Console.WriteLine(s1 == s3);    //True
Console.WriteLine(s1.Equals(s3));   //True
Console.WriteLine(Object.ReferenceEquals(s1, s3));  //False
StringBuilder sb1 = new StringBuilder("china");
StringBuilder sb2 = new StringBuilder("china");
Console.WriteLine(sb1 == sb2);      //False
Console.WriteLine(sb1.Equals(sb2)); //True
Console.WriteLine(Object.ReferenceEquals(sb1, sb2));    //False

Heap and stack analysis diagram:



1) = = it is whether the values in the stack of comparison are equal (value comparison)

2) Equals compares whether the values in the heap are equal (reference address value comparison)

3) Object. Referenceequals (obj1, obj2) compares whether memory addresses are equal

This is the end of this article about C # string and StringBuilder. For more information about C # string and StringBuilder, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

OC basis

IOS development interview essential skills chart.png What are objects and what are the objects in OC? An object is an instance of a class; Is an instance created through a class, which is generally called an instance object; Common objects in OC include instance objects, class objects, and metaclass objects; What is a class? What […]