Why are parameters "less efficient" than a regular array?

If you go right now and type string.Format

in your IDE, you will see that there are 4 different overloads: one takes a string and an object, the other takes a string and two objects, then one takes three objects, and finally the one that uses params

. According to this answer, this is because it params

generates "overhead" and some other languages ​​may not support it.

My question is, why can't the method look like this:

void Foo()
{
    Bar(1, 2, 3);
}

void Bar(params int[] args)
{
    // use args...
}

      

Essentially convert at compile time to

void Foo()
{
    Bar(new[] { 1, 2, 3 });
}

void Bar(int[] args)
{
    // use args...
}

      

? Then it would not create unnecessary costs other than creating an array (which was necessary anyway) and is fully compatible with other languages.

The number of arguments is already known at compile time, so what stops the C # compiler from doing some string substitution and makes the first script essentially syntactic sugar for the second? Why did we have to implement hidden language functions specifically to support variadic arguments?

+3


source to share


1 answer


The title makes the wrong assumption.

Both params and non-params accept an array; the difference is that the compiler will emit IL to create the array implicitly when creating a method call params

. The array is passed to both methods as one argument.

This can be seen in this .NET script (see "Tidy Up β†’ View IL").



using System;

public class Program
{
    public static void Main()
    {
        var a1 = 1;
        var a2 = 2;
        var a3 = 3; 
        with_params(a1,a2,a3);
        no_params(new [] {a1,a2,a3});
    }

    public static void with_params(params int[] x) {}
    public static void no_params(int[] x) {}
}

      

In both cases, the IL is identical; a new array is created, it is filled in and the array is passed to the called method.

There is such an "exception" for this identical generation of IL that the compiler can displace constant arrays when used in nonparametric form and use the "dup" initialization as shown here . However, in both cases, a new array is provided as an argument.

+3


source







All Articles