Which LINQ expression is faster
Posted
by
Vlad Bezden
on Stack Overflow
See other posts from Stack Overflow
or by Vlad Bezden
Published on 2011-01-06T18:38:08Z
Indexed on
2011/01/06
18:53 UTC
Read the original article
Hit count: 387
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.
© Stack Overflow or respective owner