Lot of questions has been already asked about the differences between string and string builder and most of the people suggest that string builder is faster than string. I am curious to know if string builder is too good so why string is there? Moreover, can some body give me an example where string will be more usefull than string builder?
Lot of questions has been already asked about the differences between string and string
Share
It’s not a case of which is more useful…
A
Stringis aString– one or more characters next to each other. If you want to change a string in someway, it will simply create more strings because they are immutable.A
StringBuilderis a class which creates strings. It provides a means of constructing them without creating lots of reduntant strings in memory. The end result will always be aString.Don’t do this
or
That would create 5 strings in memory (in reality, see below).
Do this:
That would create 1 string in memory (again, see below).
You can do this:
This only creates 1 string in memory.
As a side-note, creating a
StringBuilderdoes take a certain amount of memory anyway. As a rough rule of thumb:StringBuilderif you’re concatenating strings in a loop.StringBuilderif you’re concatenating a string more than 4 times.