Advantages of having both specific arguments and method overload parameters in C #

There are several examples in the .NET Framework where there are several overloads for the method, some of which use a certain number of parameters, followed by the final "catch all", where the params keyword is used. General examples of this apply to the String class, for example:

I was wondering if there is any specific reason why there are so many method overloads? At first I thought it might be related to performance; question and answers to this question SO - The cost of using parameters in C # - I would suggest.

However, I started to delve into the .NET source code using the Reference Source . I noticed this in the String class source code :

String.Concat() actually runs different code depending on how many fixed arguments are used - this, in my opinion, will definitely be an optimization. String.Format() however seems to provide a wrapper around the main param method - see below for paraphrased code:

 public static String Format(String format, Object arg0) { return Format(format, new Object[] { arg0 }); } public static String Format(String format, Object arg0, Object arg1) { return Format(format, new Object[] { arg0, arg1 }); } public static String Format(String format, Object arg0, Object arg1, Object arg2) { return Format(format, new Object[] { arg0, arg1, arg2 }); } public static String Format(String format, params Object[] args) { // Do work here... } 

Are there any performance benefits, or is it just a matter of convenience, or maybe both? In the specific case above, I do not see any obvious benefit, and this simply duplicates the work.

+3
source share
2 answers

Update: this is not String.Concat, but String.Format.

I think the reason is that all calls end in StringBuilder.AppendFormat, which is rather complicated, and this will be the main source of code duplication if you handle each number of input arguments differently.

Everything is different if you have a super-powerful API (for example, tracing), where the overhead of invoking a method using params overload is very significant. It can be up to 5 times. The same goes for implicit delegate distributions, which is common to LINQ. These temporary delegate instances are not cheap in optimized code. For example, Roslyn banned the use of LINQ due to the high implicit costs of delegate hosting.

+1
source

It allows you to create delegates for each of these signatures that invoke this method:

 Func<string, object, object> foo = string.Format; 

This will not work with the params method; you can only assign this overload to Func<string, object[]> or to the delegate who specifically provided params in his signature. You will have to create a new method that simply caused the params overload to create the delegate of the signature used in its example (possibly using lambda).

+2
source

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


All Articles