Monday, March 2, 2009

What is difference between string and string builder?

String is immutable which means once you have the content there you cannot change it, while StringBuilder is mutable because it allows you to change the content you have already placed.
The most common operation with a string is concatenation.This actvity 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".

Notice that a string allows you to change the content but off course it creates a new string reference. For example, all string methods return a new string and don't update the same string variable.
When you have huge amount of concatenation, best recommendation to go for StringBuilder!

If you are doing string concatenation StringBuilder class is far better in performance than String class.

You can use StringBuilder's Append() method to use concatenation. Both String and StringBuilder are classes used to handle strings.

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 objext 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.

0 comments:

Post a Comment

ASP.Net(1.1,2.0), C#, SQL Server2000 & 2005 Javascript, Ajax. A programming and knowledge base blog.