当我输入以下代码时:
object[] objects = new object[] { };
Run Code Online (Sandbox Code Playgroud)
Visual Studio告诉我:
避免不必要的零长度分配。请改用Array.Empty()。
使用一个在另一个之上有任何实际含义吗?
警告的原因是什么?
小智 11
您正在创建一个空数组。它将始终为空,因为您无法更改数组实例的容量(听起来很奇怪,您不能更改其长度,我不知道为什么)。每次执行此操作时,都会创建一个永远无法使用的数组实例。大量执行此操作可能会浪费GC和内存压力,从而导致警告。
与其创建空数组,不如建议使用Array.Empty <T>()。此方法使用此静态类返回一个数组
internal static class EmptyArray<T>
{
public readonly static T[] Value;
static EmptyArray()
{
EmptyArray<T>.Value = new T[0];
}
}
Run Code Online (Sandbox Code Playgroud)
由于它是静态且只读的,因此在整个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];
}
Run Code Online (Sandbox Code Playgroud)
来源:https : //referencesource.microsoft.com/#mscorlib/system/array.cs,bc9fd1be0e4f4e70
| 归档时间: |
|
| 查看次数: |
702 次 |
| 最近记录: |