string.Format performance

  • Thread starter Thread starter A.M-SG
  • Start date Start date
A

A.M-SG

Hi,

I have the following code at the heavily demanded server side service:

strResult=str1+"\\"+str2+"\\"+str3+"\\";

Would it be better (performance wise) that we change it to this:

strResult = string.Format(@"{0}\{1}\{2}\",str1,str2,str3);

Which one is faster?

Thank you,
Alan
 
string.Format takes LOT OF TIME. It has to parse the string, replace in that
strings str1,str2 and str3. It's 3-4 times slower than concatenation.

Have a look to StringBuilder which is done for that kind of operations.

Hope it helps,

Ludovic SOEUR.
 
A.M-SG said:
Hi,

I have the following code at the heavily demanded server side service:

strResult=str1+"\\"+str2+"\\"+str3+"\\";

Would it be better (performance wise) that we change it to this:

strResult = string.Format(@"{0}\{1}\{2}\",str1,str2,str3);

Which one is faster?

Why don't you set up a quick test a profile it for yourself?
Then you can post your results back here to let us know.

After all, if I am not sure which approach is faster...I test it.

Good luck
Bill
 
Ludovic said:
string.Format takes LOT OF TIME. It has to parse the string, replace in that
strings str1,str2 and str3. It's 3-4 times slower than concatenation.

Have a look to StringBuilder which is done for that kind of operations.

In this case, StringBuilder is also a waste of time - when all the
pieces are known in one go, use String.Concat (which is what the
compiler uses).

See http://www.pobox.com/~skeet/csharp/stringbuilder.html

Jon
 
Hi Bill,

I agree that I can test it myself.
My concern was if there is any special rule or technique that I am missing.
That is whay I asked for other opinions.

Beside that, now I know that string.Concat is also an option, which might
not be the fastest one.

Regards,
Alan
 
A.M-SG said:
I agree that I can test it myself.
My concern was if there is any special rule or technique that I am missing.
That is whay I asked for other opinions.

Beside that, now I know that string.Concat is also an option, which might
not be the fastest one.

String.Concat isn't *also* an option - it's the *same* option as
writing it using the "+" operator. Have a look (with ildasm) at the
code generated by the compiler for your first option.

Jon
 
string.Format takes LOT OF TIME. It has to parse the string, replace in that
string str1,str2 and str3. It's 3-4 times slower than concatenation.

Have a look to StringBuilder which is done for that kind of operations.

Hope it helps,

Ludovic SOEUR.
 
Back
Top