Possible Duplicate:
String vs StringBuilder
Hi,
I'm creating a json string. I have some json encoders that receive objects and return json string. I want to assemble these strings into one long string.
What's the difference between using a string builder and declaring a string an appending strings to it.
Thanks.
When you append to a string, you are creating a new object each time you append, because strings are immutable in .NET.
When using a StringBuilder, you build up the string in a pre-allocated buffer.
That is, for each append to a normal string; you are creating a new object and copying all the characters into it. Because all the little (or big) temporary string objects eventually will need to get garbage-collected, appending a lot of strings together can be a performance problem. Therefore, it is generally a good idea to use a StringBuilder when dynamically appending a lot of strings.
string is immutable and you allocate new memory each time you append strings.
StringBuilder allows you to add characters to an object and when you need to use the string representation, you call ToString() on it.
StringBuilder works like string.format()
and is more efficient than manually appending strings or +
ing strings. Using +
or manually appending creates multiple string objects in memory.
Copies. The stringbuilder doesn't make new copies of the strings every time; AFAIK Append just copies the bytes into a pre-allocated buffer most of the time rather than reallocating a new string. It is significantly faster! We use it at work all the time.
string.Format is using StringBuilders inside. Using StringBuilder is more optimal because you will work with it exactly as you need without the overhead that Format() needs to interpret all your args in your format string.
Imagine only that string.Format() needs to find all your "{N}" sequences in your formatting string... An extra job, huh?
Strings are immutable in C#. This makes appending strings a relatively expensive. StringBuilder
solves this problem by creating a buffer and characters are added to the buffer and converted to string
at the end of operation.
Look here for more info.
In the .NET Framework everytime you add another string to an existing string in creates a completely new instance of a string. (This takes up a lot of memory after a while)
StringBuilder uses a single instance even when you add more strings to it.
It has everything to do with performance.
String vs StringBuilder will help you understand the different between String and StringBuilder.
精彩评论