Why IEnumerable slow and List is fast?

前端 未结 4 2138
清酒与你
清酒与你 2020-12-29 06:06

Came across this code.

var dic = new Dictionary();
for(int i=0; i<20000; i++)
{
    dic.Add(i, i.ToString());
}

var list = dic.Where(         


        
4条回答
  •  温柔的废话
    2020-12-29 06:50

    LINQ uses deferred execution.
    Unless you call .ToList(), the results of a query are never stored anywhere; instead, it re-iterates the query every time you iterate the results.

    Normally, this is much faster; there is usually no reason to store all of the results in memory first.

    However, your code repeatedly iterates the query; once for each call to the Where() callback.

    You should replace that line with a Join() call and no ToList(), which will be faster than either approach.

提交回复
热议问题