If you have 5 or more strings you'd like to concatenate with String.Concat()
, then it uses Concat(String[])
.
Why not just use Concat(String[])
all the time and do away with the need for Concat(String, String)
, Concat(String, String, String)
and Concat(String, String, String, String)
.
What is Microsoft's reason for not just using Concat(String[])
whenever you want to concatenate one or more strings?
The concat() function concatenates the string arguments to the calling string and returns a new string.
It combines the contents of two or more cells into one cell without physically changing the shape of the cell and is often used to join pieces of text (called text strings or strings) from individual cells into one cell. The resulting text string is the combination of all strings in your CONCATENATE formula.
The concat() method appends (concatenate) a string to the end of another string.
According to reference source Concat(String[])
implemented this way:
public static string Concat(params string[] values)
{
int totalLength = 0; // variable to calculate total length
string[] strArray = new string[values.Length]; // second array
for (int i = 0; i < values.Length; i++) // first loop
{
string str = values[i];
totalLength += strArray[i].Length;
}
return ConcatArray(strArray, totalLength);
}
private static string ConcatArray(string[] values, int totalLength)
{
string dest = FastAllocateString(totalLength);
int destPos = 0; // variable to calculate current position
for (int i = 0; i < values.Length; i++) // second loop
{
FillStringChecked(dest, destPos, values[i]);
destPos += values[i].Length;
}
return dest;
}
Concat(String, String, String)
and similar methods are more optimized. They avoid creation of string array for parameters, they avoid loops (each loop has variable, increment and check logic), they don't use variables for calculating total string length and current position in resulting string:
public static string Concat(string str0, string str1, string str2)
{
int length = (str0.Length + str1.Length) + str2.Length;
string dest = FastAllocateString(length);
FillStringChecked(dest, 0, str0);
FillStringChecked(dest, str0.Length, str1);
FillStringChecked(dest, str0.Length + str1.Length, str2);
return dest;
}
NOTE: I skipped parameter validation code (nulls are replaced with empty strings) to show only difference.
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