Saturday, October 31, 2009

StringBuilder



Most of us when we concat any strings, we are using (+) operator (or & in vb.net) this way:


// C#
Label1.Text = Text1.Text + "@hotmail.com";
// Vb.net
Label1.Text = Text1.Text & "@hotmail.com"


But .net framework provides us another way to concat strings, using StringBuilder which is under System.Text name space, this is how to use:


//C#:
System.Text.StringBuilder mail = New System.Text.StringBuilder(Text1.Text);
mail.Append("@hotmail.com");
'VB.net:
Dim mail As New System.Text.StringBuilder(Text1.Text)
mail.Append("@hotmail.com")


What is the difference?

When using (+,&), new object will initialized every time we use this operator. But with StringBuilder, we will use the same object.

From Net Gotachas book, the auther(Venka) assume simple concat operations within loop. And he run the loop using different maximum values of loops. This is snap shoot from the book representing the execution time:






3562.933 second is equal to 59.4 minutes. So will you still use (+,&)?

Finaly, StringBuilder gives us another operations such as Replace, Insert and Remove, you can find all about it with a graphs represent the diferent from this article in CodeProject:
http://www.codeproject.com/KB/cs/StringBuilder_vs_String.aspx


0 comments:

Post a Comment