What is difference between:
String.Concat
,String.Format
,+
operator.which one is more efficient in every condition whether long or short string concatenation.
string.Concat
just concatenates strings together. It provides no conversions beyond calling ToString
, no formatting etc.
string.Format
is a much richer, allowing format patterns etc.
When you use the +
operator in C# source code, the compiler converts that into calls to String.Concat
- it's not an execution time operator in the way that it is in, say, decimal
.
So this:
string result = x + y + z;
is compiled into this:
string result = string.Concat(x, y, z);
In terms of efficiency, clearly calls to string.Concat
and using +
can be equivalent. I'd generally expect that to be faster than string.Format
but the difference would be negligible in most cases. You should write the clearest, most maintainable code you can first (which often means using string.Format
) and then micro-optimize only when you have test data to show that you need to optimize that particular piece, and then only retain the optimization once you've proved it helps.
Note that one area where a bit of optimization can make a huge difference is repeated concatenation, usually in a loop. This code is horribly inefficient:
string result = "";
foreach (var x in y)
{
// Do some processing...
string z = ...;
result += z;
}
This ends up having to copy an intermediate string on each iteration. In these situations, either use StringBuilder
, or use a LINQ query to represent the items you'll end up needing to concatenate and then either string.Join
or string.Concat
to perform the concatenation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With