Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of String.Concat(String, String, String, String)

Tags:

string

c#

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?

like image 264
David Klempfner Avatar asked Jun 19 '14 00:06

David Klempfner


People also ask

What is the use of concat in string?

The concat() function concatenates the string arguments to the calling string and returns a new string.

What is the point of concatenation?

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.

What is the purpose of a concat in Java?

The concat() method appends (concatenate) a string to the end of another string.


1 Answers

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.

like image 111
Sergey Berezovskiy Avatar answered Sep 21 '22 17:09

Sergey Berezovskiy