当我键入以下代码时:
object[] objects = new object[] { };
Visual Studio告诉我:
避免不必要的零长度分配。请改用Array.Empty()。
使用一个比另一个有任何实际意义吗?
警告的原因是什么?
你正在创建一个空数组。因为你无法改变数组实例的容量,所以它总是空的(只是说你不能改变它的长度听起来很奇怪,我不知道为什么)。每次执行此操作时,都会创建另一个永远不能使用的数组实例。这样做可能会导致GC和内存压力浪费,从而产生警告。
而不是创建空数组,只需使用Array.Empty <T>(),因为它建议。此方法使用此静态类返回一个数组
internal static class EmptyArray<T>
{
public readonly static T[] Value;
static EmptyArray()
{
EmptyArray<T>.Value = new T[0];
}
}
因为它是静态的和只读的,所以在整个appdomain中只有这个空数组的一个实例。空数组本质上是不可变的,因此缓存实例不是问题。它允许你放弃算法中的特殊套管空数组创建,如果你发现自己正在观察一个创建大量空数组的优雅代码路径。
Enumerable.Empty <T>()是Linq to Objects的等价物,对于不浪费空事物的分配也很有用。
使用Array.Empty有助于避免不必要的内存分配。请参阅下面的.NET库本身的代码:
[Pure]
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public static T[] Empty<T>()
{
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == 0);
Contract.EndContractBlock();
return EmptyArray<T>.Value;
}
...
// Useful in number of places that return an empty byte array to avoid unnecessary memory allocation.
internal static class EmptyArray<T>
{
public static readonly T[] Value = new T[0];
}
资料来源:https://referencesource.microsoft.com/#mscorlib/system/array.cs,bc9fd1be0e4f4e70