Search code examples
c#optimizationcollectionsc#-3.0

Does C# Collection Initialization Syntax Avoid Default Initialization Overhead


When you use the new C# collection initialization syntax:

string[] sarray = new[] { "A", "B", "C", "D" };

does the compiler avoid initializing each array slot to the default value, or is it equivalent to:

string[] sarray = new string[4];  // all slots initialized to null
sarray[0] = "A";
sarray[1] = "B";
sarray[2] = "C";
sarray[3] = "D";

Solution

  • The compiler still uses the newarr IL instruction, so the CLR will still initialize the array.

    Collection initialization is just compiler magic - the CLR doesn't know anything about it, so it'll still assume it has to do sanity clearance.

    However, this should be really, really quick - it's just wiping memory. I doubt it's a significant overhead in many situations.