About Me

Professional Practical HumanBeing

Monday, January 3, 2011

What is the Main difference between String and StringBuilder and why do we use StringBuilder

Note 1 :-

Use StringBuilder if you are planning to change/concatenate a string a lot, as it's slightly more efficient.

This is because a string type is immutable within the CLR, this means that if you do this:

string test = String.Empty();

test = test + "Hello";

test = test + " World!";

You've actually created 3 strings, one for each time it's been changed

Whereas

StringBuilder test = new StringBuilder();

test.Append("Hello");

test.Append(" World!");

This has created just ONE StringBuilder

StringBuilder in the Java world is called StringBuffer. I think!

Hope this has cleared it up!

Note 2:-

String are Immutable (Not Modifiable). If you try to modify  the string it actually creates 
a new string and the old  string will be then ready for garbage collection.
StringBuilder when instantiated, creates a new string with  predefined capacity and upto that 
capacity it can  accodomate string without needing to create a new memory  location for the 
string....i mean it is modifiable and can  also grow as and when needed. 
When the string needs to be modified frequently, preferably  use StringBuilder as its optimized 
for such situations.

Note 3 :-

Both String and StringBuilder are classes used to handle the strings.
The most common operation with a string is concatenation. This activity has to be 
performed very efficiently.
When we use the "String" object to concatenate two strings, the first string is 
combined to the other string by creating a new copy in the memory as a string object,
and then the old string is deleted.
This process is a little long. Hence we say "Strings are immutable".
When we make use of the "StringBuilder" object, the Append method is used. 
This means, an insertion is done on the existing string.
Operation on StringBuilder object is faster than String operations, as the copy 
is done to the same location. Usage of StringBuilder is more efficient in case large
amounts of string manipulations have to be performed.

No comments:

Post a Comment