2
哪種方法更快或者是否都編譯爲相同的IL?Foreach循環,在循環語句之外派生迭代集合會更快嗎?
var myCollection = new Dictionary<string, string>(){{"a", "aa"}, {"b", "bb"}, {"c", "bb"}};
foreach (var uniqueItem in myCollection.Values.Distinct())
{
//do something
}
var myCollection = new Dictionary<string, string>() { { "a", "aa" }, { "b", "bb" }, { "c", "bb" } };
var uniqueItems = myCollection.Values.Distinct();
foreach (var uniqueItem in uniqueItems)
{
//do something
}
在IL中,無論迭代次數如何,調試模式下的額外賦值都會進行一次? –
是的,它將* myCollection.Values.Distinct()*的值存儲在堆棧上,而無需再次調用該方法。 – Elisha
非常感謝... –