This is not a case that is more useful ...
A String
- String
- one or more characters next to each other. If you want to change the string in some way, it will simply create more lines, because they are immutable .
A StringBuilder
is a class that creates strings. It provides the means to build them without creating a large number of repeated lines in memory. The end result will always be String
.
Do not do this
string s = "my string"; s += " is now a little longer";
or
s = s + " is now longer again";
This would create 5 lines in memory (in effect, see below).
Do it:
StringBuilder sb = new StringBuilder(); sb.Append("my string"); sb.Append(" is now a little longer"); sb.Append(" is now longer again"); string s = sb.ToString();
This would create line 1 in memory (see below).
You can do it:
string s = "It is now " + DateTime.Now + ".";
This creates only 1 line in memory.
As a side note, creating a StringBuilder
anyway requires a certain amount of memory. As a rough rule of thumb:
- Always use
StringBuilder
if you are concatenating strings in a loop. - Use
StringBuilder
if you are concatenating a string more than 4 times.
David Neale Jun 18 2018-10-18 13:07
source share