Are simple LINQ queries on an IEnumerable<T>
lightweight or heavyweight? How do they compare to writing for
or foreach
loops by hand? Is there a general guideline for when to prefer LINQ versus manual searching?
For example:
var lowNums =
from n in numbers
where n < 5
select n;
Compared to:
List<int> lowNums = new List<int>();
foreach (int n in numbers)
{
if (n < 5)
{
lowNums.Add(n);
}
}
I was talking to a coworker about LINQ and he expressed some hesitation about using it. He guessed that there might be a lot going on "behind the scenes" in order to support everything LINQ can do.
Is there a significant performance difference between the above examples? Are there any good resources that talk about LINQ performance on collections? A simple Google search for linq performance turned up some seemingly outdated articles.
See Question&Answers more detail:os