Which LINQ expression is faster
- by Vlad Bezden
Hi All
In following code
public class Person
{
public string Name { get; set; }
public uint Age { get; set; }
public Person(string name, uint age)
{
Name = name;
Age = age;
}
}
void Main()
{
var data = new List<Person>{ new Person("Bill Gates", 55),
new Person("Steve Ballmer", 54),
new Person("Steve Jobs", 55),
new Person("Scott Gu", 35)};
// 1st approach
data.Where (x => x.Age > 40).ToList().ForEach(x => x.Age++);
// 2nd approach
data.ForEach(x =>
{
if (x.Age > 40)
x.Age++;
});
data.ForEach(x => Console.WriteLine(x));
}
in my understanding 2nd approach should be faster since it iterates through each item once and first approach is running 2 times:
Where clause
ForEach on subset of items from where clause.
However internally it might be that compiler translates 1st approach to the 2nd approach anyway and they will have the same performance.
Any suggestions or ideas?
I could do profiling like suggested, but I want to understand what is going on compiler level if those to lines of code are the same to the compiler, or compiler will treat it literally.
Thanks in advance for your help.