在LINQ查詢中調用ToList()或ToArray()更好嗎? - Is it better to call ToList() or ToArray() in LINQ queries?

問題:

I often run into the case where I want to eval a query right where I declare it.我經常遇到我想在聲明它的地方評估一個查詢的情況。 This is usually because I need to iterate over it multiple times and it is expensive to compute.這通常是因爲我需要對其進行多次遍歷,並且計算起來很昂貴。 For example:例如:

string raw = "...";
var lines = (from l in raw.Split('\n')
             let ll = l.Trim()
             where !string.IsNullOrEmpty(ll)
             select ll).ToList();

This works fine.這很好。 But if I am not going to modify the result, then I might as well call ToArray() instead of ToList() .但是,如果我不打算修改結果,那麼我不妨調用ToArray()而不是ToList()

I wonder however whether ToArray() is implemented by first calling ToList() and is therefore less memory efficient than just calling ToList() .但是我不知道ToArray()是否通過首先調用ToList() ToArray()來實現,因此與僅調用ToList()相比,內存效率較低。

Am I crazy?我瘋了嗎? Should I just call ToArray() - safe and secure in the knowledge that the memory won't be allocated twice?我應該只調用ToArray() -在不會兩次分配內存的情況下安全可靠嗎?


解決方案:

參考一: https://stackoom.com/question/4diY
參考二: Is it better to call ToList() or ToArray() in LINQ queries?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章