Difference between string and stringBuilder: stringbuilder

Source: Internet
Author: User

Difference between string and stringBuilder: stringbuilder

The String object cannot be changed. Each time you use one of the methods in the String class or perform operations (such as assignment and concatenation), You must create a new String object in the memory, in this case, you need to allocate a new space for the new object. StringBuilder represents a variable character string. This class cannot be inherited. If you need to modify the String repeatedly, the system overhead associated with creating a new String object may be very expensive. If you want to modify the string without creating a new object, you can use System. text. stringBuilder class. For example, the StringBuilder class can be used to improve performance when many strings are connected in a loop.

1. Set the capacity and length

StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ", 25); Method 1
MyStringBuilder. Capacity = 25; method 2
The EnsureCapacity method can be used to check the current capacity of the 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.

2. Modify the StringBuilder string

Use method name
StringBuilder. Append: Append the information to the end of the current StringBuilder.
StringBuilder. AppendFormat replaces 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 a specified number of characters from the current StringBuilder object
StringBuilder. Replace replaces the specified character at the specified index

Append
The Append method can be used to add the string representation of a text or object to the end of a string represented by the current StringBuilder object. The following example initializes a StringBuilder object as "Hello World" and appends some text to the end of the object. Space will be automatically allocated as needed.

[C #]
StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");
MyStringBuilder. Append ("What a beautiful day .");
Console. WriteLine (MyStringBuilder );
 
In this example, Hello World! What a beautiful day. displayed on the console.

AppendFormat
The AppendFormat method adds text to the end of StringBuilder and implements the IFormattable interface. Therefore, the standard format string described in the formatting section is acceptable. You can use this method to customize the variable format and append these values to the end of StringBuilder. The following example uses the AppendFormat method to place an integer set to the currency value format at the end of StringBuilder.

[C #]
Int MyInt = 25;
StringBuilder MyStringBuilder = new StringBuilder ("Your total is ");
MyStringBuilder. AppendFormat ("{0: C}", MyInt );
Console. WriteLine (MyStringBuilder );

In this example, the Your total is $25.00 is displayed on the console.

Insert
The 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 to the sixth position of StringBuilder.

[C #]
StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");
MyStringBuilder. Insert (6, "Beautiful ");
Console. WriteLine (MyStringBuilder );
 
In this example, Hello Beautiful World! Displayed on the console.

Remove
You can use the Remove method to Remove a specified number of characters from the current StringBuilder. The removal process starts from the specified index starting from scratch. The following example uses the Remove Method to shorten StringBuilder.

[C #]
StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");
MyStringBuilder. Remove (5, 7 );
Console. WriteLine (MyStringBuilder );

In this example, Hello is displayed on the console.

Replace uses the Replace method to Replace the characters in the StringBuilder object with another specified character. The following example uses the Replace method to search for StringBuilder objects and find all exclamation point characters (!), Use the question mark character (?) To replace them.

[C #]
StringBuilder MyStringBuilder = new StringBuilder ("Hello World! ");
MyStringBuilder. Replace ('! ','? ');
Console. WriteLine (MyStringBuilder );

In this example, Hello World? Displayed on the console.

3. Convert the Stringbuilder string to the string form.

String = StringBuilder. toString ();

Instance:

string text = "";StringBuilder sbi = new StringBuilder("");DateTime s1 = System.DateTime.Now;for (int i = 0; i < 50000; i++){sbi.Append(i);}DateTime s11 = System.DateTime.Now;Console.WriteLine(s11-s1);s1 = System.DateTime.Now;for (int i = 0; i < 50000; i++){text = text + i;}s11 = System.DateTime.Now;Console.WriteLine(s11 - s1);

  

 

 

 


What is the difference between string and stringbuilder in C #?

The Stringbuilder class is directly used for string operations. For example
(1) string aa = "123456 ";
(2) aa ++ = "789 ";

(3) StringBuilder text = new StringBuilder ("123456", 12 );
(4) text. Append ("789 ");
If you output aa, and text, you will find that their output content is the same.
But the aa operation is actually: first, allocate an address space in the memory, and the size of the space is 6.
Then, perform the aa + = "789"; operation, which is the connection string, "123456" and "789" and re-allocate the address in the memory. Point the memory address of aa to the memory address of "123456789.

That is to say, in the memory, there are actually two spaces allocated to the north. The first memory space was automatically processed by the C # garbage disposal system later,

If we use a three or four-sentence program to implement this process, it does not allocate memory space again,
It operates in the memory space of text. Here we need to explain that StringBuilder can allocate its own size during the life variable process. If the actual content exceeds the memory space,
It will automatically double.

Through the above example, we can know that the superiority of StringBuilder is:
First, he does not need to allocate memory every time. Therefore, the system does not have to deal with garbage;
Second, when we need to perform multiple operations on a string multiple times, its efficiency is far higher than that of string.

Hope the answer is helpful to you;

What is the difference between String Stringbuffer and StringBuilder?

Variable Character Sequence for ava. lang. StringBuffer thread security. A String buffer similar to a String, but cannot be modified. Although it contains a specific character sequence at any time point, the length and content of the sequence can be changed by calling some methods.

The string buffer can be safely used for multiple threads. These methods can be synchronized as necessary, so all the operations on any specific instance are in serial order, this sequence is consistent with the method call sequence of each involved thread.

The main operations on StringBuffer are append and insert methods. You can reload these methods to accept any type of data. Each method can effectively convert the given data to a string, and then append or insert the character of the string into the string buffer. The append method always adds these characters to the end of the buffer, while the insert method adds the characters at the specified point.

For example, if z references a string buffer object whose current content is "start", this method calls z. append ("le") causes the string buffer to contain "startle", while z. insert (4, "le") will change the string buffer to include "starlet ".

Generally, if sb references an instance of StringBuilder, sb. append (x) and sb. insert (sb. length (), x) have the same effect.

If an operation is performed on the source sequence (such as append or insert in the source sequence), the operation is only performed on the string buffer for this operation, rather than on the source.

Each string buffer has a certain capacity. As long as the length of the Character Sequence contained in the string buffer does not exceed this capacity, no new internal buffer array needs to be allocated. If the internal buffer overflow occurs, the capacity increases automatically. From JDK 5, a equivalence class used by a single thread is added for this class, that is, StringBuilder. Compared with this class, the StringBuilder class should be used first, because it supports all the same operations, but because it does not execute synchronization, It is faster.

Java. lang. StringBuilder a variable character sequence. This class provides a StringBuffer-compatible API, but does not guarantee synchronization. This class is designed as a simple replacement of StringBuffer, used when the string buffer is used by a single thread (this is common ). If possible, we recommend that you use this class first, because in most implementations, It is faster than StringBuffer.

The main operations on StringBuilder are append and insert methods. You can reload these methods to accept any type of data. Each method can effectively convert the given data to a string, and then append or insert the character of the string to the string generator. The append method always adds these characters to the end of the generator, while the insert method adds the characters at the specified point.

For example, if z references a string generator object whose current content is "start", this method calls z. append ("le") will make the string generator contain "startle", while z. insert (4, "le") changes the string generator to include "starlet ".

Generally, if sb references the StringBuilder instance, sb. append (x) and sb. insert (sb. length (), x) have the same effect. Each string generator has a certain capacity. As long as the length of the Character Sequence contained in the string generator does not exceed this capacity, no new internal buffer needs to be allocated. If the internal buffer overflow occurs, the capacity increases automatically.

It is not safe to use StringBuilder instances for multiple threads. If you need such synchronization, we recommend that you use the rest of the full text>

Related Article

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.