Did you ever wonder if there is a noticeable difference between:
List<int> a = [1, 2, 3];
// And
List<int> b = new() {1,2,3};
Let's find out:
Lowered version
We can make the answer pretty obvious, so we just lower the code:
int num = 3;
List<int> list = new List<int>(num);
CollectionsMarshal.SetCount(list, num);
Span<int> span = CollectionsMarshal.AsSpan(list);
int num2 = 0;
span[num2] = 1;
num2++;
span[num2] = 2;
num2++;
span[num2] = 3;
num2++;
List<int> list2 = new List<int>();
list2.Add(1);
list2.Add(2);
list2.Add(3);
Where list
is our a
and list2
is b
. So collections expressions ([1,2,3]
) are "smarter" and faster in the sense that they preallocate the list with the exact number of elements we want to add. The collection initializer doesn't do that for one simple reason: The compiler by its spec is required to call the Add
method for each element in the initializer. Is the performance benefit worth it? Well that is up to you - it is measurable for sure!