Florian
Florian

Reputation: 4728

StringBuilder, differences between two syntaxes

Is there a difference between :

StringBuilder requete = new StringBuilder();
requete.Append(" INSERT into " + listeLibelleTable[index] + " ( ");

and

StringBuilder requete = new StringBuilder();
requete.Append(" INSERT into ");
requete.Append(listeLibelleTable[index]);
requete.Append(" ( ");

When I say "difference" I mean in terms of performance, if this code is in a loop for example.

I think these line

requete.Append(" INSERT into " + listeLibelleTable[index] + " ( ");

is resolved at compile time so It should not be any impact in terms of performance but I'm not sure of that

Upvotes: 0

Views: 277

Answers (4)

Oded
Oded

Reputation: 499002

Unless listeLibelleTable[index] can indeed be resolved at compile time (which I greatly doubt), using the string concatenation seems to be counter productive to the use of the StringBuilder.

In your second example you are concatenating a string and then appending it instead of appending to the StringBuilder.

In either case, you should probably use AppendFormat for readability:

requete.AppendFormat(" INSERT into {0} ( ", listeLibelleTable[index]);

Upvotes: 4

Mujah Maskey
Mujah Maskey

Reputation: 8804

String concatenation will create new String object and copy exisiting value, and despose old string. show it will be slow. check http://kaioa.com/node/59 for reference

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500635

Your first code is performing the concatenation, building a complete string and then appending it to the StringBuilder. Assuming you're also going to append other things, the second form could be a little bit faster... it doesn't need the temporary string with the result of that part of the concatenation.

On the other hand, if you're performing a database operation, the difference is going to be immeasurably small.

Upvotes: 1

danyolgiax
danyolgiax

Reputation: 13086

I think doing this:

" INSERT into " + listeLibelleTable[index] + " ( "

you use more memory to store result of concat operation!

Upvotes: 0

Related Questions