posted on Friday, July 18, 2003 8:21 AM
by
admin
Quick Tip: String vs. StringBuilder
Ok, this is just a quick tip since I'm tired.
We're going discuss why you should ALWAYS use a StringBuilder (part of System.Text namespace) when doing any string manipulation.
Put simply, a string type is immutable and a StringBuilder is NOT.
Immutable means that after created it cannot be modfied, changed, etc. - This is what a string type is, if you add even just one character to a string using either the + or &
myString = myString & "HI"
A new string is created (an additional OBJECT is created)
A StringBuilder is NOT immutable (Mutable), so you can add, remove, modify, etc. a StringBuilder object and new objects will NOT be created. So, if you need to dynamically construct a string or manipulate one always use a StringBuilder object.
C# Example:
StringBuilder sb = new StringBuilder("You can pass in a string to the contstructor");
sb.Append(" and then add some more");
There are many other methods and properties of the stringbuilder object you should check out to make your life easier:
Check StringBuilder Class Browser