What problem does StringBuilder solve?

Why should I use StringBuilder only to add strings? For example, why should you use:

StringBuilder sb = new StringBuilder; sb.Append("A string"); sb.Append("Another string"); 

over

 String first = "A string"; first += "Another string"; 

?

+4
source share
4 answers

The StringBuilder documentation explains its purpose:

The String object is immutable. every time you use one of the methods in the System.String Class, you create a new string object in memory, which requires a new allocation of space for this new object. In situations where you need to re-modify a string, the overhead associated with creating a new String object can be expensive. The System.Text.StringBuilder class can be used when you want to change a row without creating a new object. For example, using the StringBuilder class can improve performance when combining many lines into a loop.

+10
source

In a simple case like yours, it really doesn't matter. But, as a rule, strings are immutable, which means that every change to a string variable will create a new buffer in memory, copy new data and leave the old buffer. In case you perform a lot of string manipulations, this slows down your program and leads to a lot of abandoned string buffers that need to be collected by the garbage collector.

+5
source

Mostly problems with immutable string. It also provides methods for easier string manipulation. Take a look at Using the Stringbuilder Class

0
source

StringBuilder changed. There is no line. Therefore, any operation on a line creates a new object. In the 2nd example, 2 objects are created (one for each row). If the first creates only one object.

0
source

Source: https://habr.com/ru/post/1346027/


All Articles