For performance reasons, use StringBuilder
when concatenating strings, especially in a loop.
Allocations are expensive and when you do s = s1 + s2
to concatenate strings, you create a new string object, which needs to be allocated.
string s1 = "string1";
string s2 = "string2";
string s3 = s1 + s2; // "string1string2"
Concatenating strings using a StringBuilder can offer performance advantages over simple string concatenation using \\+
. This is due to the way memory is allocated. Strings are reallocated with each concatenation, StringBuilders allocate memory in blocks only reallocating when the current block is exhausted. This can make a huge difference when doing a lot of small concatenations.
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
sb.Append(i);
sb.Append(" ");
}
Console.WriteLine(sb.ToString()); // "1 2 3 4 5 "
Calls to Append()
can be daisy chained, because it returns a reference to the StringBuilder
:
StringBuilder sb = new StringBuilder();
sb.Append("some string ")
.Append("another string");
The String.Join
method can be used to concatenate multiple elements from a string array.
string[] value = {"apple", "orange", "grape", "pear"};
string separator = ", ";
string result = String.Join(separator, value, 1, 2);
Console.WriteLine(result);
Produces the following output: “orange, grape”
This example uses the String.Join(String, String[], Int32, Int32)
overload, which specifies the start index and count on top of the separator and value.
If you do not wish to use the startIndex and count overloads, you can join all string given. Like this:
string[] value = {"apple", "orange", "grape", "pear"};
string separator = ", ";
string result = String.Join(separator, value);
Console.WriteLine(result);
which will produce;
apple, orange, grape, pear
You can concatenate strings using string formatting::