Reason 11 overloads string.Concat

I just noticed that there are 11 method overloads string.Concat()

public static string Concat(IEnumerable<string> values);
public static string Concat<T>(IEnumerable<T> values);
public static string Concat(object arg0);
public static string Concat(params object[] args);
public static string Concat(params string[] values);
public static string Concat(object arg0, object arg1);
public static string Concat(string str0, string str1);
public static string Concat(object arg0, object arg1, object arg2);
public static string Concat(string str0, string str1, string str2);
public static string Concat(object arg0, object arg1, object arg2, object arg3);
public static string Concat(string str0, string str1, string str2, string str3);

What is the reason for this? Both

public static string Concat(params object[] args);
public static string Concat<T>(IEnumerable<T> values);

should be the only necessary because they are just as comfortable / powerful. MSDN does not give an answer to this, and if you remove 9 “duplicate” overloads from the framework, no one will notice.

+4
source share
2 answers

The primary motivation for solving this implementation is performance.

As you rightly noted, there can only be two:

public static string Concat(params object[] args);
public static string Concat<T>(IEnumerable<T> values);

# "params enumerable", IEnumerable<T> T[] - . .

, .

string x = Foo();
string y = Bar();
string z = x + y;

? ToString codegen'd

string x = Foo();
string y = Bar();
object[] array = new string[2];
array[0] = x;
array[1] = y;
string z = string.Concat(array);

: . , . , , .. , ..

; , , , . , , , , , , : .

, . , Concat.

- - - , . , ? . ToString ? , . null, ToString.

, . ToString , , , . , . , , , ..

, , .

. ?

, , :

static string Concat(string, string)

:

string x = Foo();
string y = Bar();
string z = string.Concat(x, y);

, , , . , ToString , , , , ..

, : , params, , .

, . . , , , , . , ; , .

, , 2006 .

https://ericlippert.com/2013/06/17/string-concatenation-behind-the-scenes-part-one/

+16

(IEnumerable<String>) (IEnumerable<T>) .

  • IEnumerable<String> , / , - , , .
  • IEnumerable<T> - Object[] ).

IEnumerable<T> , , # params , (, String[] Object[]), .

, params Object[] params String[] Object arg0, Object arg1 String arg0, String arg1, params , , , , ; , 1, 2, 3 4 (, , 95% ), .

, ( params ) : ` params` # ? - , .

, # params IEnumerable (, IEnumerable #), JIT .

+1

Source: https://habr.com/ru/post/1660398/


All Articles