检查 List<T> 是否为空时空合并运算符的性能

我有一个List<int>从方法中获取它的值


List<int> items = GetIntegerStuff();

所以当前避免 NullReference 异常的代码看起来像这样


if (items == null)

{

    items = new List<int>();

}

我把它改成这个是因为我喜欢短代码——但我的高级开发人员说这很糟糕,因为如果有项目(大约 90% 的请求都会发生),整个列表将被分配,这对性能不利。这是真的?


items = items ?? new List<int>();


aluckdog
浏览 186回答 2
2回答

慕森卡

这些是可能的方法://APPROACH 1List<int> items = GetIntegerStuff();if (items == null){&nbsp; &nbsp; items = new List<int>();}//APPROACH 2List<int> items = GetIntegerStuff() ?? new List<int>();//APPROACH 3List<int> items = GetIntegerStuff();items = items ?? new List<int>();//APPROACH 4List<int> items = GetIntegerStuff();items = items == null ? new List<int>() : items;我会选择2号,从我的角度来看,它是最干净的。为了完整起见,在某些情况下您可以找到类似的内容:class Program{&nbsp; &nbsp; private static List<int> _items = new List<int>();&nbsp; &nbsp; private static List<int> Items&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return _items;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; set&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _items = value ?? new List<int>();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; static void Main(string[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //APPROACH 5&nbsp; &nbsp; &nbsp; &nbsp; Items = GetIntegerStuff();&nbsp; &nbsp; }&nbsp; &nbsp; private static Random Random = new Random();&nbsp; &nbsp; private static List<int> GetIntegerStuff()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; switch (Random.Next(0, 2))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case 0:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new List<int>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}这对性能有害吗?List<int> items = GetIntegerStuff();items = items ?? new List<int>();不,但它实际上会执行更多关于以下方面的指令:List<int> items = GetIntegerStuff();if (items == null){&nbsp; &nbsp; items = new List<int>();}或者List<int> items = GetIntegerStuff() ?? new List<int>();
打开App,查看更多内容
随时随地看视频慕课网APP