String Concat vs. Plus operator

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

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
 
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.

Assuming that without seeing what the + operator does in the same
situation is a problem.

In fact, the + operator calls the more specific version of
String.Concat as well, without creating an array.
 
Back
Top