亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

檢查 List<T> 是否為空時空合并運算符的性能

檢查 List<T> 是否為空時空合并運算符的性能

C#
aluckdog 2021-10-09 16:52:20
我有一個List<int>從方法中獲取它的值List<int> items = GetIntegerStuff();所以當前避免 NullReference 異常的代碼看起來像這樣if (items == null){    items = new List<int>();}我把它改成這個是因為我喜歡短代碼——但我的高級開發人員說這很糟糕,因為如果有項目(大約 90% 的請求都會發生),整個列表將被分配,這對性能不利。這是真的?items = items ?? new List<int>();
查看完整描述

2 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

這些是可能的方法:


//APPROACH 1

List<int> items = GetIntegerStuff();

if (items == null)

{

    items = new List<int>();

}


//APPROACH 2

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


//APPROACH 3

List<int> items = GetIntegerStuff();

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


//APPROACH 4

List<int> items = GetIntegerStuff();

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

我會選擇2號,從我的角度來看,它是最干凈的。


為了完整起見,在某些情況下您可以找到類似的內容:


class Program

{

    private static List<int> _items = new List<int>();


    private static List<int> Items

    {

        get

        {

            return _items;

        }


        set

        {

            _items = value ?? new List<int>();

        }

    }


    static void Main(string[] args)

    {

        //APPROACH 5

        Items = GetIntegerStuff();

    }


    private static Random Random = new Random();

    private static List<int> GetIntegerStuff()

    {

        switch (Random.Next(0, 2))

        {

            case 0:

                return null;

                break;

            default:

                return new List<int>();

                break;

        }

    }

}

這對性能有害嗎?


List<int> items = GetIntegerStuff();

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

不,但它實際上會執行更多關于以下方面的指令:


List<int> items = GetIntegerStuff();

if (items == null)

{

    items = new List<int>();

}

或者


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


查看完整回答
反對 回復 2021-10-09
  • 2 回答
  • 0 關注
  • 203 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號