Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

benefits of using a stringbuilder [duplicate]

Tags:

c#

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.

like image 612
frenchie Avatar asked Dec 03 '22 08:12

frenchie


1 Answers

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.

like image 135
driis Avatar answered Dec 24 '22 10:12

driis