Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between String.Concat ,string.format and +?

What is difference between:

  • String.Concat,
  • String.Format,
  • + operator.

which one is more efficient in every condition whether long or short string concatenation.

like image 607
Abhi_Dev Avatar asked Feb 15 '12 07:02

Abhi_Dev


1 Answers

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.

like image 168
Jon Skeet Avatar answered Sep 25 '22 08:09

Jon Skeet