Possible Duplicate:
Should LINQ be avoided because it's slow?
I love LINQ. As I read in another post today “it's the best thing since sliced bread” and I totally agree. But at the company I work everyone else seems to hate LINQ.
A few weeks ago I was using ReSharper for the first time and while I was coding ReSharper suddenly told me my foreach-loop could be converted into a LINQ expression. This was like magic to me and I showed my colleague. Much to my suprise he said “I wish it would work the other way around and turn LINQ into loops. That would be much faster!”
So is LINQ-to-Objects really so slow? I tried out myself. When I run the following sample a few times I get Elapsed Ticks around 350.
Stopwatch sw = new Stopwatch();
List<Person> personList = new List<Person>();
for (int i = 0; i < 5000; i++)
{
Person p = new Person() {ID = i};
personList.Add(p);
}
sw.Start();
Person searchPerson = null;
foreach (Person person in personList)
{
if (person.ID == 4321)
{
searchPerson = person;
break;
}
}
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
If I change the loop to a LINQ-Query (Resharper will do that for me) I get ElapsedTicks around 900. More than twice as much as with the loop.
Person searchPerson = personList.FirstOrDefault(person => person.ID == 4321);
As is seems LINQ is indeed slower and if you use it a lot this could be an issue. And at our company we have lots of data. So is it the right decision to avoid LINQ or are we doing something wrong?