22

C#/.NET has variadic function parameters by passing an Array type by-reference (as opposed to C/C++ which just places all of the values directly on the stack, for better and for worse).

In the C# world this has a neat advantage of allowing you to call the same function with either 'raw' arguments or a reusable array instance:

CultureInfo c = CultureInfo.InvariantCulture;

String formatted0 = String.Format( c, "{0} {1} {2}", 1, 2, 3 );

Int32 third = 3;
String formatted0 = String.Format( c, "{0} {1} {2}", 1, 2, third );

Object[] values = new Object[] { 1, 2, 3 };
String formatted1 = String.Format( c, "{0} {1} {2}", values );

This means that the generated CIL is equivalent to:

String formatted0 = String.Format( c, "{0} {1} {2}", new Object[] { 1, 2, 3 } );

Int32 third = 3;
String formatted0 = String.Format( c, "{0} {1} {2}", new Object[] { 1, 2, third } );

Object[] values = new Object[] { 1, 2, 3 };
String formatted1 = String.Format( c, "{0} {1} {2}", values );

Which means that (in a non-optimizing JIT compiler) every call will allocate a new Object[] instance - though in the third example you're able to store the array as a field or other reusable value to eliminate the new allocation on every call to String.Format.

But in the official CLR runtime and JIT are any optimizations done to eliminate this allocation? Or perhaps is the array tagged specially so that it will be deallocated as soon as execution leaves the scope of the call-site?

Or, perhaps, because the C# or JIT compiler knows the number of arguments (when used "raw") could it do the same thing as the stackalloc keyword and place the array on the stack, and thus not need to deallocate it?

1

4 Answers 4

16

Yes, a new array is allocated every time.

No, no optimizations are done. There is no "interning" of the kind you suggest. After all, how could there be? The receiving method can do anything with the array, including mutating its members, or reassigning array entries, or passing a reference to the array on to others (without params then).

No special "tagging" of the kind you suggest, exists. These arrays are garbage collected in the same way as anything else.


Addition: There is of course one special case where "interning" of the kind we discuss here, could be easy to do, and that is for length-zero arrays. The C# compiler could call Array.Empty<T>() (which returns the same length-zero array each time) instead of creating a new T[] { } whenever it encountered a call to params where a length-zero array is needed.

The reason for this possibility is that length-zero arrays are truly immutable.

Of course "interning" of length-zero arrays would be discoverable, for example the behavior of this class would change if the feature were to be introduced:

class ParamsArrayKeeper
{
  readonly HashSet<object[]> knownArrays = new HashSet<object[]>(); // reference-equals semantics

  public void NewCall(params object[] arr)
  {
    var isNew = knownArrays.Add(arr);
    Console.WriteLine("Was this params array seen before: " + !isNew);
    Console.WriteLine("Number of instances now kept: " + knownArrays.Count);
  }
}

Addition: Given that the "strange" array covariance of .NET does not apply to value types, are you sure your code:

Int32[] values = new Int32[ 1, 2, 3 ];
String formatted1 = String.Format( CultureInfo.InvariantCulture, "{0} {1} {2}", values );

works as intended (if the syntax is corrected to new[] { 1, 2, 3, } or similar, this will go to the wrong overload of String.Format, for sure).

3
  • 1
    re the no interning: big deal! If a method alters an array without knowing where it comes from and what will happen to it afterwards, and expects that to OK, it deserves whatever it gets.
    – jmoreno
    Jul 30, 2016 at 23:57
  • 1
    Quite interestingly, I tested your ParamsArrayKeeper code and in fact when called multiple times with empty parameters it actually increases its size only the first time! Also further adding an Array.Empty<object>() to it didn't change its size, meaning that the params is doing exactly what you said it could be doing! It's worth noting that I made this test using Unity 2018.2, running on the Mac editor using Mono with the .NET 4.x scripting environment. Oct 14, 2018 at 15:04
  • 1
    @JorgeGalvão Wow, I also see this right now, with the .NET Framework under Windows 10, 1803, with Visual Studio 2017, 15.8.7. If I use (object[])(Enumerable.Empty<object>()), the cast succeeds, and I get a different instance, but a fixed one. I wonder if this optimized behavior is new. I do not think I saw it to years ago when I wrote this post, but I am not sure (also not sure if I even ran my code back then). Oct 15, 2018 at 17:45
8

Yes, a new array will be allocated on every call.

Besides complexity of inlining methods with params, which was explained by @PeterDuniho, consider this: all performance-critical .NET methods which have params overloads have overloads taking just one or several arguments too. They wouldn't do this if automatic optimization was possible.

  • Console (also String, TextWriter, StringBuilder etc.):

    • public static void Write(String format, params Object[] arg)
    • public static void Write(String format, Object arg0)
    • public static void Write(String format, Object arg0, Object arg1)
    • public static void Write(bool value)
  • Array:

    • public unsafe static Array CreateInstance(Type elementType, params int[] lengths)
    • public unsafe static Array CreateInstance(Type elementType, int length)
    • public unsafe static Array CreateInstance(Type elementType, int length1, int length2)
    • public unsafe static Array CreateInstance(Type elementType, int length1, int length2, int length3)
  • Path:

    • public static String Combine(params String[] paths)
    • public static String Combine(String path1, String path2)
    • public static String Combine(String path1, String path2, String path3)
  • CancellationTokenSource:

    • public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens)
    • public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token1, CancellationToken token2)
  • etc.

P. S. I admit it doesn't prove anything, as optimization may have been introduced in later versions, but it's still something to consider. CancellationTokenSource was introduced in relatively recent 4.0.

1
  • 1
    Agree that these are performance optimizations. But it doesn't have to be related to the creation of the array. It could be useful to write optimized algorithms for most common cases. E.g. one argument may be trivial to handle while a n arguments needs looping, dynamic memory usage etc. Apr 6, 2017 at 13:33
5

But in the official CLR runtime and JIT are any optimizations done to eliminate this allocation?

You'd have to ask the authors. But given how much effort would have to go into that, I doubt it. The declaring method has to have access to the array, and will retrieve members using array syntax. So any optimization would necessarily wind up having to rewrite the method logic to translate array access to direct parameter access.

Furthermore, the optimization would have to take place globally, taking into account all callers of the method. And it would have to detect whether the method ever passes the array to anything else.

This just doesn't seem like a feasible optimization, especially given how little value it would add to runtime performance.

Or perhaps is the array tagged specially so that it will be deallocated as soon as execution leaves the scope of the call-site?

There's no need to tag the array "specially", as the garbage collector already will automatically handle the scenario well. In fact, the array can be garbage collected as soon as it's no longer used in the declaring method. No need to wait until the method returns.

2

The compiler currently creates a new object prior to the method call. It is not required to do so, and it is possible that the JITter optimizes it away.

See https://github.com/dotnet/roslyn/issues/36 for a discussion on possible changes performance improvements with params.

4
  • The C# compiler is required to create a new array, under the C# versions 1.0 through 6.0 (which means all existing versions of C#). The jitter could in principle do magical things, but in this case it will not. Your link provides an interesting discussion of some new params features that may or may not be added to C# in a future version. One can imagine some way to keep a variable-length "list" of arguments on the call stack, without allocating a new object on the heap (that is going to be short-lived in many typical use cases). But this is not something that exists in C# and CLR today. Jul 31, 2016 at 11:09
  • It is required to do something that is the equivalent of creating a new array, it is not actually required to create a new array. For instance, it could in theory pre-allocate the the arrays for usage in a loop. Static analysis could lead to a single array creation outside of a loop, and reuse of the array for each invocation.
    – jmoreno
    Jul 31, 2016 at 14:01
  • If anything other than creating a new array each time the method is called again with the same parameters, is done, the method receiving the array might notice the difference. The C# Language Specification says a new array is to be created. So since the C# compiler cannot look ahead and see if the receiving method will actually check if it is a new instance, the C# compiler will have a tough time coming up with any "optimization". The runtime and jitter may cheat in principle, but it will not (in this case) as far as I know. See my answer for an example of a method that reveals "cheating". Jul 31, 2016 at 15:27
  • The receiving method can't check for newly created, it can only pass it as a parameter to another method -- the compiler can certainly verify that. As you say, it currently doesn't but there is no fundamental reason why it can't attempt to do so and if successful reuse the array. Not much different than inlining.
    – jmoreno
    Jul 31, 2016 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.