问题描述
是否在集合类型上使用支撑式初始化程序设置了它的容量,还是还需要指定它的容量?
Does using the braced initializer on a collection type set it's capacity or do you still need to specify it?
也就是说,是:
var list = new List<string>(){ "One", "Two" };
结果与以下相同:
var list = new List<string>(2){ "One", "Two" };
推荐答案
对象初始化程序仅调用 Add
。
Object initializer simply calls Add
for each item.
var list = new List<string>{ "One", "Two", "Three" };
如您所见,在这种情况下,无参数构造函数称为:
As you can see, in this case parameterless constructor is called:
L_0000: nop
L_0001: newobj instance void [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
L_0006: stloc.1
L_0007: ldloc.1
L_0008: ldstr "One"
L_000d: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
L_0012: nop
L_0013: ldloc.1
L_0014: ldstr "Two"
L_0019: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
L_001e: nop
L_001f: ldloc.1
L_0020: ldstr "Three"
L_0025: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
L_002a: nop
L_002b: ldloc.1
因此,您应该手动设置容量:
So, you should set capacity manually:
var list = new List<string>(5){ "One", "Two", "Three" };
编译为:
L_0000: nop
L_0001: ldc.i4.5
L_0002: newobj instance void [mscorlib]System.Collections.Generic.List`1<string>::.ctor(int32)
// rest is same
因此,算法非常明显-它调用构造函数您指定了(默认情况下为无参数),然后为每个项目调用添加
。
So, algorithm is pretty obvious - it calls constructor which you specified (parameterless by default) and then calls Add
for each item.
注意:我知道,该默认值 List< T>
的容量为4,我验证了如果我们在初始化程序中传递4个以上的项目(例如,编译器根据项目数确定要调用哪个构造函数)会发生什么情况,但是结果是相同的-默认情况下将调用无参数构造函数。
NOTE: I know, that default capacity is 4 for List<T>
and I verified what happens if we pass more than 4 items in initializer (e.g. maybe compiler determines which constructor to call depending on items count) but result is same - parameterless constructor is called by default.
我认为集合初始值设定项的目的是创建小的集合(1-8个项目),因此会有一点性能影响(如果将8个项目传递给初始值设定项,则仅调整大小)。没有人期望您将对100个项目使用就地初始化。而且,如果要执行此操作,则应使用适当的collection构造函数。
I think purpose of collection initializers is creating small collections (1 - 8 items), thus there will be a little performance impact (only one resize if you will pass 8 items into initializer). Nobody expects you will use in-place initialization with 100 items. And if you are going to do that, you should use appropriate constructor of collection.
这篇关于在集合类型上使用支撑式初始化程序会设置初始容量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!