June 7, 2012

StringBuilder - Overview, Tips & Tricks


MSDN describes StringBuilder is a Mutable (Changeable) string of characters.
   1:  [SerializableAttribute]
   2:  [ComVisibleAttribute(true)]
   3:  public sealed class StringBuilder : ISerializable

The term "Sealed" describes in above syntax, cannot be inherited.

What is the use of string builder ?

StringBuilder is a Mutable object for concatenating strings without need of new reference (New memory) for every concatenation.

Now your brain may arise a question, the same (Concatenation) can be achieved from system.String class then what is the use of StringBuilder.

Why StringBuilder when there is String ?

1. Strings are immutable (Unchangeable) so StringBuilder is best for concatenating unknown no of iterations.
ie. If you try to change it with the Concatenation or with the Replace, PadLeft, PadRight or substring etc, it finally ended with entirely new string. The existing memory remains same until garbage collected. Allocations of new memory costly in terms of both memory and performance.
2. StringBuilder can modify string without having to allocate new memory. It is made to do complex and large concatenation. But keep large-object-heap in mind.

Now you may ask

Why String ? Can't we use StringBuilder everywhere ?

We must really think about the overhead of initialization. StringBuilder doubles its capacity, meaning it reallocates its buffers so it can store twice as many characters each time.
Don't use in smaller concatenations.

Where we use StringBuilder ?

1. When you don't have a loop, generally you should avoid StringBuilder.
2. Don't use StringBuilder in zippy concatenation.
   1:  string str = string1(...) + string2(...)  + string3(...)  + string4(...)
StringBuilder won't help. Because this is single concatenation, ordinary string contate better than string builder
but the pattern like this, surely you need string builder
   1:  foreach(...)
   2:  {
   3:      if(..) str  += string1(...)
   4:      if(..) str  += string2(...)
   5:      if(..) str  += string3(...)
   6:      if(..) str  += string4(...)
   7:  }

StringBuilder Tips:

1. Don't Use + (plus) inside StringBuilderAppend()
2. For lesser concatenation string builder slow down. because of allocation of the StringBuilder object.
3. String Builder uses internal memory to concatenate string, if your concatenation increses string builder performance increases and vice versa.
4. StringBuilder has no advance knowledge of the required result buffer size and has to reallocate each time the buffer size is exceeded.

No comments:

Post a Comment

Recommended Post Slide Out For Blogger