Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Worth having a StringBuilder for 5 concatenations? [duplicate]

Tags:

java

c#

Possible Duplicate:
At what point does using a StringBuilder become insignificant or an overhead?

Related/Duplicate Questions
String vs StringBuilder
At what point does using a StringBuilder become insignificant or an overhead?

As plain as possible I have this method 1:

cmd2.CommandText = ("insert into " + TableName + " values (" + string.Join(",", insertvalues) + ");");

I am wondering if method 2 be faster if I would do:

StringBuilder sb2 = new StringBuilder();
sb2.Append("insert into ");
sb2.Append(TableName);
sb2.Append(" values (");
sb2.Append(string.Join(",", insertvalues));
sb2.Append(");");

cmd2.CommandText = sb2.ToString();
like image 323
Pentium10 Avatar asked Feb 12 '10 09:02

Pentium10


3 Answers

You could also try String.Format, which I believe uses a StringBuilder internally but has increased readability.

cmd2.CommandText = string.Format("insert into {0} values ({1});", TableName, string.Join(",", insertvalues));

(This is for C#)

like image 180
Andy Shellam Avatar answered Oct 21 '22 17:10

Andy Shellam


For small programs this will be a premature optimization.

If you want to take into consideration these kinds of optimization then better measure it, because this depends on the size of the string concatenated also, apart from the number or appends.

like image 3
rahul Avatar answered Oct 21 '22 15:10

rahul


Besides that IMO the StringBuilder method looks and reads better the StringBuilder does outperform string concatenation after 5 to 10 added strings according to http://dotnetperls.com/stringbuilder-performance

like image 2
Kenny Eliasson Avatar answered Oct 21 '22 15:10

Kenny Eliasson