Sunday, 5 June 2016

Difference between string and String builder

Show below for demonstration of  Difference between string and String builder.

String belongs to system namespace. Its commonly use reference type.  If we are not perform any operation string is fast.  We can initialize the string directly like below.

string str = "name";

String is immutable type, once created the memory location of string can’t be modify . If we perform any operation like insert, replace or concatenation, it will discard the current memory location and assign the new memory location.

string str = "hi";
str += "Greeting";
str += "name";

String Builder
String builder belongs to System.Text namespace. We use stringbuilder if perform any string operation or string manipulation. Initialization of string builder is compatibility Slow as compare to string. We can initialize string builder like:

StringBuilder sb = new StringBuilder();

StringBuilder is mutable type, Once created the memory location at time of inialization can’t be change till the size of memory exist.  We can defined the buffer size of memory allocation in string builder like.

StringBuilder sb = new StringBuilder(1200);

If perform any string manipulation operation like append. It is faster as compare to string if we perform any string manipulation operations,

StringBuilder sb = new StringBuilder();

Namespace System
Namespace System.Text
It is immutable
It is mutable
String manipulation operation is slow
String manipulation operation is fast.
Initialize Operation like
string str = "hi";
Initialize operation like
StringBuilder sb = new StringBuilder();
No Append keyword to join string.
Having append keyword to join string.

No comments:

Post a Comment


You will like to read it