June 7, 2012

StringBuilder - Overview, Tips & Tricks

StringBuilder

MSDN describes StringBuilder is a Mutable (Changeable) string of characters.
Syntax:
   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.
eg:
   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.

C# - Large Object Heap

Large Object Heap

Objects larger than some 85,000 bytes get allocated on a separate heap, called the large object heap. This heap has one special characteristic: it never gets compacted, because that would be too costly, moving those large objects would take too long. Without compaction, there are many situations, both theoretical and practical, that may and eventually will lead to an out-of-memory situation due to fragmentation.
StringBuilder in C# 4.0 this issue is fixed by using linked list.

String - Intern Pool

Intern Pool

The common language runtime conserves string storage by maintaining a table, called the Intern pool, that contains a single reference to each unique literal.
Eg:
   1:  using System;
   2:   
   3:  namespace ProveStringIsImmutable
   4:  {
   5:      class Program
   6:      {
   7:          static void Main(string[] args)
   8:          {
   9:              string foo = "I`m a good boy";
  10:              string bar = "I`m a good boy";
  11:              Console.WriteLine(Object.ReferenceEquals(foo, bar));
  12:              foo = foo + " with some stuff";
  13:              Console.WriteLine(Object.ReferenceEquals(foo, bar));
  14:          }
  15:      }
  16:  }
  17:   
  18:  //Output:
  19:  //--------------------
  20:  //true
  21:  //false

Initially foo and bar have unique string literals, so foo and bar got same reference. In Brief While try to assigning bar, CLR smart enough to check the given literals already exists in intern table or not, if yes then, returns same existing memory reference of unique string literals.

Here We can also able to prove string immutability , when we try to alter foo, The resulted reference not match with old one, that means CLR assigned new memory reference for altered string.
"If we try to change or modify a string, it finally ended with entirely new string - String Immutability"

June 4, 2012

String Builder Append vs String Concate vs String Format vs StringBuilder AppendFormat vs Ordinary Concatenation

Which one is faster method.?
   1:  string str1 = string.Format("{0}{1}{2}{3}{4}","String1","String2","String3","String4","String5");
   2:  string str2 = new StringBuilder().Append("String1").Append("String2").Append("String3").Append("String4").Append("String5");
   3:  string str3 = string.Concat(new string [] { "String1", "String2", "String3", "String4", "String5"});
   4:  string str4 = "String1" + "String2" + "String3" + "String4" + "String5";

You may think string builder or string concate but result is over 1 lakh iterations traditional "+" Operator faster in terms of memory and time.

Why traditional "+" Operator faster:
Reason behind traditional "+" Operator faster is it used String.Concat with length.
compiler convert this piece of code:
   1:  string str = "String1" + "String2" + "String3" + "String4" + "String5";
to this
   1:  string str = String.Concat(new Object[] { "String1", "String2", "String3", "String4", "String5"});

To do traditional zippy concatenation like above, don't confuse yourself, just use traditional "+" concatenation that's enough, c# does jobs for you..

June 1, 2012

Design Patterns

What is pattern..? or What is the use of pattern..?

Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.