For the case of C # :
String.Format
internally uses StringBuilder
:
public static string Format(IFormatProvider provider, string format, params object[] args)
{
if ((format == null) || (args == null))
{
throw new ArgumentNullException((format == null) ? "format" : "args");
}
StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
builder.AppendFormat(provider, format, args);
return builder.ToString();
}
Operator +
becomes String.Concat
When we have this code example:
string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;
At the moment of compiling it, it becomes:
string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);
The official documentation says:
An object concatenation operation String
always creates a new object from the existing string and new data. An object StringBuilder
keeps a buffer to accommodate the concatenation of new data. New data is added to the buffer if space is available; Otherwise, a new larger buffer is assigned, the original buffer data is copied into the new buffer, and the new data is added to the new buffer.
Therefore:
Executing a concatenation operation for a String
or StringBuilder
object depends on the frequency of the memory allocations.
(Now it makes sense this answer from samjudson , where he mentions that the first execution and the order matter and will always take more time)
In summary
Depends on the objective of your test, since at the end of the day the format you give your String
also consumes resources, since it is not the same to add a simple string that adds a string that has some specific format ( in this case it would be StringBuilder.Append()
versus StringBuilder.AppendFormat()
). Some people base the technique to be used according to the number of items they use at that moment . Like a StringBuilder
has many more functionalities than simply the concatenation.
Which one should you choose? The answer is depends. For your exposed case I suggest using String.Concat
, for more detailed cases the best would be StringBuilder
.
References: