String Concat vs. Plus operator

Tech-Archive recommends: Speed Up your PC by fixing your registry



Does anybody have a definitive, backable answer to which way is better when
concating strings (String.Concat vs. +). You can easily prove one faster
than the other in contrived examples. I'm interested in real-world examples.
My experiments have shown that both versions are equivalent.

Given:

void TestStringOp ( string value1, string value2, string value3 )
{
string result = value1 + " " + value2 + " and " + value1 + " " + value3;
}

void TestStringConcat ( string value1, string value2, string value3 )
{
string result = String.Concat(value1, " ", value2, " and ", value1, " ",
value3);
}

Dumping the IL for TestStringOp reveals that this is converted to the
equivalent of this:

string[] temp = new string[] { value1, " ", value2, " and ", value1, " ",
value3 };
string result = String.Concat(temp);

Dumping the IL for TestStringConcat reveals that the exact same code is
generated. Therefore the performance is identical. The bad thing about this
is that internally String.Concat will allocate another string array and copy
the strings into it before finally calling the fast string allocator.

The only time I think Concat is a better choice is when the # of strings to
concat is 4 or less. In this case the optimized version of the concat
routine is called. Therefore my running rule is that if concatenating 4 or
less strings then use String.Concat otherwise it doesn't matter.

Understandably timing this code won't be very revealing since the optimizer
will probably get rid of all the code anyway but by comparing the IL I should
be able to overlook the optimizations that will be done.

Anybody have definitive, backable answers to this? Thanks,
Michael Taylor - 4/18/05
.



Relevant Pages

  • Re: TeamB, Borland, admit obvious
    ... > strings as using the Concat function: ... The plus operator is faster than Concat. ... > Microsoft has nothing to offer Visual Basic developers other than hack. ...
    (borland.public.delphi.non-technical)
  • Re: Convert a string to a vector?
    ... > the toStringmethod of vector class and then used the concat() ... > method of the String class to concatenate the strings. ... a new data vector or array, ...
    (comp.lang.java.programmer)
  • Re: String.Concat vs String.Format
    ... ramadu wrote: ... Using strings is part of every day life. ... Well, the Concat call is faster, *but* it's unlikely to ever be ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: String Concatenation in VB.NET
    ... Sriram Krishnan ... Microsoft Student Ambassador ... >> if you just concat two strings, ...
    (microsoft.public.dotnet.framework.performance)
  • Re: how to concat two strings into one?
    ... Brandon ... > I am a newer for PERL. ... I want to concat two strings into one string, ...
    (comp.lang.perl.misc)