Why should I use the StringBuilder class instead of the String class?


Why these two classes are different, as it seems to me that they could be a single class.

For example, the method Append , it seems to me that it does the same thing as the + operator.

asked by anonymous 03.10.2015 / 03:14

1 answer


Basically to avoid the problem of Shlemiel the painter's algorithm.

The string in C # is immutable . When you add new parts to the string , you need to re-allocate memory and copy all existing content to add new content. Of course there is some optimization to not happen that much, but it happens much more than is acceptable in most situations. Imagine that every time the allocation is larger and it is spending more time, making its use impractical.

The type StringBuilder is changeable. Then only the new parts are allocated and it connects these parts. When there is change in snippets of text, it actually changes instead of creating new text.

Of course, it is not in any situation that StringBuilder will be clearly more efficient. Many programmers who already know the problem feel that any concatenation should use it. That is not true. If you know how many and which excerpts to concatenate, you do not need to use this type . So it's usually only advantageous in large or potentially large ties.

Note that internally there are differences and you can not simply use the contents of a StringBuilder where something like string is expected. A conversion is required. So in cases of few concatenations the advantage is not great either.

Some of the information passed is implementation details, so it's possible that each implementation is a bit different.

It is also clear that the goal is different when we look at the methods of one type and the other. We do not have the same set of possible behaviors. Some methods make more sense in StringBuilder (the main ones are Append , Insert , Replace and Remove ), which is not a suitable type to do all sorts of string manipulation > which has many more methods of basic manipulation.

I will not go into many details here because there are several answers on the subject with information that serves this question, even when speaking another language.

More details about its operation (it's Java but it's almost the same).

03.10.2015 / 03:39