Question

What is the difference between strings and string builder in .NET?

Was it helpful?

Solution

A string is an immutable type. It has bad performance characteristics when performing lots of string manipulation like concatenation.

Stringbuilders on the other hand overcome this weakness by keeping a growing buffer so that each concatenation is less likely to require a new string to be allocated.

Since string builders add some overhead, they are only really necessary when some significant string work is to be done (e.g. in a loop). If your code is fast, don't worry about it. If it's not, use a profiler to see if this issue matters in your case.

One final note: this answer really has nothing to do with ASP.NET--this is true of strings in all of .net and lots of other languages, too.

OTHER TIPS

http://en.csharp-online.net/CSharp_String_Theory%E2%80%94String_vs._StringBuilder

Basically, Strings are immutable - every time you manipulate one is needs to be recreated in memory. StringBuilder is easier on memory and in nearly all cases, much faster when you're dealing with repetitive string concatenation and other manipulative operations.

You may find some better discussion in this SO post: String vs. StringBuilder.

string is immutable and stringbuilder is mutable.

In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created.

Immutable objects are often useful because some costly operations for copying and comparing can be omitted, simplifying the program code and speeding execution. However, making an object immutable is usually inappropriate if the object contains a large amount of changeable data. Because of this, many languages allow for both immutable and mutable objects.

Each time a concatenation is made to a string object a new string object is created with a new reference and it will be assigned to the object. The older object will still there be in memory.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top