7

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();
Community
  • 1
  • 1
Pentium10
  • 204,586
  • 122
  • 423
  • 502
  • 3
    The only way to know is to measure it and see. However you will find that what ever difference there might be is so small as to be neglibable – Binary Worrier Feb 12 '10 at 09:17
  • A very 'popular' question here: http://stackoverflow.com/questions/73883/string-vs-stringbuilder http://stackoverflow.com/questions/529999 – o.k.w Feb 12 '10 at 09:20
  • Near duplicate: http://stackoverflow.com/questions/1532461 – Peter Mortensen Feb 12 '10 at 09:20
  • 2
    The speed of this string concatenation will be a tiny, tiny fraction of the speed of actually running the command, so you're **definitely** optimizing the wrong thing. – Joachim Sauer Feb 12 '10 at 09:21
  • 9
    Also: don't build SQL statements like this, because you **will** be vulnerable to SQL injection attacks this way: http://en.wikipedia.org/wiki/SQL_injection – Joachim Sauer Feb 12 '10 at 09:22

8 Answers8

12

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#)

Andy Shellam
  • 15,403
  • 1
  • 27
  • 41
  • Using Formatting is definitely the way to go if you want readability. Further, the StringBuilder class has its own method, AppendFormat that uses the same syntax. I have dealt with code written with hundreds of lines of Append. It is a nightmare, although at least easily re-factored. A good mix of AppendFormat and reusable helper functions (good programmers don't copy and paste) can really make it much more manageable. Just Don't overdo it with the amount of arguments in a single format. The key consideration should always be readability and maintainability. – Marcus Andrén Feb 12 '10 at 10:30
  • Definitely, Marcus. Any performance improvement you get using StringBuilder vs string.Format will be nothing compared to the time you would lose trying to work out what the completed string from a StringBuilder will look like. ALWAYS always think of readability and maintainability over millisecond performance improvements. – Andy Shellam Feb 12 '10 at 11:04
3

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.

rahul
  • 184,426
  • 49
  • 232
  • 263
  • 7
    It seems fashionable around here to parrot this **premature optimization** argument *ad infinitum* every time someone mentions performance. Why discourage people from trying to understand how to make their code faster, so that when the time arises *where it will matter*, they have a larger range of tools at their disposal? – Winston Smith Feb 12 '10 at 09:43
  • 1
    Because those people will then always use those tools because they might be faster and then they just end up creating horrible to read code because they use string builders instead of string concatenation everywhere but their applications performance still sucks because they don't optimize the real bottlenecks, instead only replacing _every_ result = string1 + string2 with StringBuilder temp = new StringBuilder(); temp.Append(string1); temp.Append(string2); result = temp.ToString(); –  Feb 12 '10 at 10:31
2

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

Kenny Eliasson
  • 2,047
  • 15
  • 23
2

From here:

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuffer class and its append method.

So it would seem that the compiler is using StringBuffer on your behalf anyway.

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
2

In C# an expression in the form "a" + b + "c" is optimized by the compiler into String.Concat("a", b, "c") so you will not get intermediary strings. This would be more efficient than a StringBuilder.

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111
1

A good compiler should optimize this for you - but don't take my word for it when you can easily find out for yourself.

Unless you are doing this in a tight loop, then the difference in performance is likely to be insignificant.

String concatenation of values is usually a bad way to construct SQL statements when you could use bind variables instead. This allows the database to optimize the queries. Using bind is likely to make a much bigger difference than optimizing your string construction - and with bind you only need to construct the string once per session instead of once per query.

richj
  • 7,499
  • 3
  • 32
  • 50
0

Use String.format.

String.format("insert into {0} values({1});",TableName,string.Join(",", insertvalues));

It's more readable.

Christoph
  • 1,927
  • 15
  • 14
0

Your two methods will not differ in performance, the reason is that your string is concatenaled in 1 expression, and the compiler will create a StringBuilder for that expression. The following are equivalent and result in the same code:

String s1 = "five" + '=' + 5;

String s2 = new StringBuilder().append("five").append('=').append(5).toString();

If your code splits up the expresion, for instance in a loop, creating your own StringBuilder will perform better, the naive version using string + concatenation results after compilation in code like:

String s3 = "";

for (int n = 0; n < 5; n++) {

    s3 = new StringBuilder(s3).append(getText(n)).append('=').append(n).append("\n").toString();
}

creating your method using an explicit StringBuilder can save creation of unnecessary StringBuilder objects.

For simple methods you normally do not have to optimise string concatenation yourself, but in those situations where the code is on the critical path, or where you are forced to use many different string expression to build up your end result, it is a good to know what happens under the hood so you can decide whether it is worth the extra effort.

Note that StringBuffer is thread-safe, while StringBuilder is not. StringBuilder is the faster choice for situations where multi-threaded access is not an issue.

rsp
  • 23,135
  • 6
  • 55
  • 69