Wednesday, May 30, 2012

Difference between String and StringBuilder in .net


Both String and StringBuilder are classes used to handle strings.
String concatenation is one of the commonly used operations among programmers.If you don't handle the string concatenation in .NET properly,it may decrease the performance of an application.
Once created a string cannot be changed.
A StringBuilder can be changed as many times as necessary. 

String : The most common operation with a string is concatenation.
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. So we say "Strings are Immutable".

Ex :
string strNumber = "";
for(int i = 0; i<1000; i++)
{
   
strNumber = strNumber + i.ToString();
}



StringBuilder : 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. 


Ex :
StringBuilder sbNumber = new StringBuilder(10000);
for(int i = 0; i<1000; i++)
{
   
sbNumber.Append(i.ToString());
}

No comments:

Post a Comment

Comments

Search

Custom Search
Protected by Copyscape Plagiarism Software