![](/img/trans.png)
[英]ConcurrentBag<T> and lock(List<T>) which is faster to add or remove?
[英]Why is LINQ Where search query faster on List<> compared to ConcurrentBag<>
我有一個包含1億個實體的List集合。 當我執行簡單的Linq Where()
查詢時,搜索需要大約48個滴答(10,000個滴答= 1毫秒),而在ConcurrentBag
放置1億個實體,然后在其上使用相同的搜索查詢需要58個滴答。
我多次重復測試,差異幾乎保持不變。 有人可以詳細說明為什么會有性能差異?
從ConcurrentBag<T>.GetEnumerator
的規范:
枚舉表示行李內容的時刻快照。 調用GetEnumerator后,它不會反映對集合的任何更新。 枚舉器可以安全地與讀取和寫入包同時使用。
在內部, ConcurrentBag
每次枚舉時都會創建一個新列表 ,以及其他操作。
來自ReferenceSource.microsoft.com :
public IEnumerator<T> GetEnumerator()
{
// Short path if the bag is empty
if (m_headList == null)
return new List<T>().GetEnumerator(); // empty list
bool lockTaken = false;
try
{
FreezeBag(ref lockTaken);
return ToList().GetEnumerator();
}
finally
{
UnfreezeBag(lockTaken);
}
}
private List<T> ToList()
{
Contract.Assert(Monitor.IsEntered(GlobalListsLock));
List<T> list = new List<T>();
ThreadLocalList currentList = m_headList;
while (currentList != null)
{
Node currentNode = currentList.m_head;
while (currentNode != null)
{
list.Add(currentNode.m_value);
currentNode = currentNode.m_next;
}
currentList = currentList.m_nextList;
}
return list;
}
當然,這必須比枚舉簡單列表慢。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.