Reprinted from Https://www.cnblogs.com/cang12138/p/7323709.html
Read Catalogue
- 1. When do I use string? When do you use StringBuilder?
- The difference between 2.String and StringBuilder
- Summarize
1. When do I use string? When do you use StringBuilder?
Once a string is created, it cannot be resized, and each time one of the methods in the System.String class is used, a new string object is created in memory, which requires a new space to be allocated for the new object. The overhead associated with creating a new string object can be very expensive in situations where you need to perform repeated modifications to the string. If you want to modify a string without creating a new object, you can use the System.Text.StringBuilder class. For example, using the StringBuilder class can improve performance when you concatenate many strings together in a loop.
So the addition or deletion of the string is not frequent, just a few fixed string accumulation of time do not need to StringBuilder, after all, StringBuilder initialization also takes time. If you add or delete strings more frequently then use StringBuilder.
String a1 = "abc"; Allocates a fixed memory size a1+= "DEF"; Create a new memory allocation A1, the cost is more expensive StringBuilder SB = new StringBuilder (20); Specifies the allocation size of SB. Append (' abc '); Assigned to the heap area sb. Append (' Def '); is not destroyed, but is appended directly to the back.
Summary: The above A1 and SB in the output of the same results. But there is a big difference between memory allocations.
Back to Top
the difference between 2.String and StringBuilder
After a string declaration, the size in memory is non-modifiable, while the StringBuilder can be free to extend the size (string is allocated on the stack, StringBuilder is allocated in the heap area)
1) string (detailed in C # string string)
string S1 = new String (new char[] {' C ', ' h ', ' I ', ' n ', ' a '}); String s2 = "abc";
2) StringBuilder
StringBuilder sb = new StringBuilder (5); When the allocation size is specified, performance is improved. It does not redistribute space for itself until the capacity is reached. If the system exceeds the specified size, the current size is multiplied and 10,15,20. It is recommended to specify size SB. Append (' China '); sb. capacity = 25; In addition, you can use the read/write capacity property to set the maximum length of an object. 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. 5 ways to modify the contents of a StringBuilder stringbuilder.append//Append the information to the end of the current StringBuilder. Stringbuilder.appendformat//replaces the format specifier passed in the string with the formatted text. Stringbuilder.insert//Inserts a string or an object into the current StringBuilder object at the specified index. 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//append method can be used to add a string representation of text or an object to the end of a string represented by the current StringBuilder object. The following example initializes a StringBuilder object to "Hello world" and then appends some text to the end of the object. The space is automatically allocated as needed. StringBuilder sb = new StringBuilder ("Hello world!"); Sb. Append ("What a Beautiful Day."); Console.WriteLine (SB); Result: Hello world! What is a beautiful day. The AppendFormat//appendformat method adds text to the end of the StringBuilder and implements the IFormattable interface, so the standard format string described in the formatting section can be accepted. You can use this method to customize the format of a variable and append these values to the back of the StringBuilder. The following example uses the AppendFormat method to place an integer value formatted as a currency value to the end of StringBuilder. int MyInt = 25; StringBuilder sb = New StringBuilder ("Your Total is"); Sb. AppendFormat ("{0:c}", MyInt); Console.WriteLine (SB); Result: The Your total is $25.00//insert//insert method adds a string or object to the specified position in the current StringBuilder. The following example uses this method to insert a word into the sixth position of the StringBuilder. StringBuilder sb = New StringBuilder ("Hello world!"); Sb. Insert (6, "Beautiful"); Console.WriteLine (SB); Result: Hello Beautiful world! The Remove//remove method removes the specified number of characters from the current StringBuilder, and the removal process starts at the specified zero-based index. The following example uses the Remove method to shorten the StringBuilder. StringBuilder sb = New StringBuilder ("Hello world!"); Sb. Remove (5,7); Console.WriteLine (SB); Result: Hello//replace//Using the Replace method, you can replace the characters within the StringBuilder object with another specified character. The following example uses the Replace method to search for a StringBuilder object, find all the exclamation-point characters (!), and use the question mark character (?). To replace them. StringBuilder SB = new StringBuilder ("Hello world!"); Sb. Replace ('! ', '? '); Console.WriteLine (SB); Result: Hello world?
Let's look at how it's allocated in memory:
3) Knowing how they are distributed, you can distinguish between "= =", "Equals", "Object.referenceequals (OBJ1,OBJ2)".
(1) before this = =: Maybe Java programmers will feel a little bit ignorant when they see this. In Java, the string type is placed in the heap. While C # is different, Microsoft optimizes the string type
(2) Microsoft uses a hash table when working with strings: what is it? The simple understanding is that when you create the string "China", when you create the string again, the compiler will not open up new memory to store it. It points directly to the address you created for the first time.
(3) Look at 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)); Trueconsole.writeline (Object.referenceequals (S1, S2)); Trueconsole.writeline ("--------------------------"); 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 the above S1 = = S3 is True 。 Console.WriteLine (S3. Equals (S4)); Trueconsole.writeline (Object.referenceequals (S3, S4)); Falseconsole.writeline ("--------------------------"); Console.WriteLine (S1 = = S3); Trueconsole.writeline (S1. Equals (S3)); Trueconsole.writeline (Object.referenceequals (S1, S3)); Falseconsole.writeline ("---------StringBuilder-----------------"); StringBuilder sb1 = new StringBuilder ("China"); StringBuilder SB2 = new StringBuilder ("China"); Console.WriteLine (SB1 = = SB2); FalsecOnsole. WriteLine (SB1. Equals (SB2)); Trueconsole.writeline (Object.referenceequals (SB1, SB2)); False
Heap and Stack analysis diagram:
Back to Top
Summary
1) = = It is a comparison of the values within the stack is equal (value comparison)
2) equals it compares the values in the heap for equality (reference address value comparison)
3) object.referenceequals (OBJ1,OBJ2) It is compared to whether memory addresses are equal
C # string and StringBuilder