Click here to Skip to main content
15,850,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a list of People type. The people type has two properties. Name and Age. Of course, Name is string type and Age is int type.

Now I want to multiply 2 to the Age of all.

So I want to use foreach loop, each item times 2.

The other option is to use lambda expression.
C#
return list.(x=>x*2);


Which way is better?

What I have tried:

I was advised by an "expert". The answer was to use lamada expression rather than foreach loop.
But I still have not found a strong reason to support it.
Posted
Updated 27-Jul-17 4:20am
v2

1 solution

It depends.

Here is a performance comparison:
C#
class Program
{
    static void Main(string[] args)
    {
        var persons = new List<Person>();
        for (int i = 0; i < 10000; i++)
        {
            persons.Add(new Person { Name = $"person {i}", age = i });
        }

        var sw = new Stopwatch();

        sw.Start();
        for (int i = 0; i < 1000; i++)
        {
            for (int j = 0; j < 10000; j++)
            {
                persons[j].age ++;
            }
        }
        sw.Stop();
        Console.WriteLine($"for loop: {sw.ElapsedMilliseconds} ms");

        sw.Reset();
        sw.Start();
        for (int i = 0; i < 1000; i++)
        {
            foreach (var person in persons)
            {
                person.age++;
            }
        }
        sw.Stop();
        Console.WriteLine($"foreach loop: {sw.ElapsedMilliseconds} ms");

        sw.Reset();
        sw.Start();
        for (int i = 0; i < 1000; i++)
        {
            persons.ForEach(person => person.age++);
        }
        sw.Stop();
        Console.WriteLine($"Linq ForEach: {sw.ElapsedMilliseconds} ms");

        Console.ReadKey();
    }
}

class Person
{
    public string Name { get; set; }
    public int age { get; set; }
}

Output:
for loop: 453 ms
foreach loop: 527 ms
Linq ForEach: 839 ms

It is easy to see which is the best to use.
 
Share this answer
 
v2
Comments
Sharp Ninja 27-Jul-17 8:54am    
This is an overly simplistic use case, which is going to be subject to the body of the action being invoked through a delegate instead of falling directly into the code. On a more complex body, especially one with nested loops, then the lower overhead iterating the outer loop will be more significant. However, your answer does directly answer the OP's question than mine does with the scope of the question.

Another thing to consider is using .AsParallel and then running Parallel.ForEach() on the loop if the body of the loop is a standalone unit of work, which in this case it is. Please add that use case to your example and re-run.
Graeme_Grant 27-Jul-17 9:35am    
Yes, the answer was within the scope of the question. :)
BillWoodruff 27-Jul-17 12:10pm    
keep in mind that timing in .NET can be heavily skewed by:

1. running in Debug mode rather than in Release mode

2. not doing an initial run so JIT compilation is accounted for

3. not using explicit control of garbage collection

I would expect Linq to start "paying the rent" when multiple access to complex IEnumerable objects is done, and, for simple traversal and simple manipulation of a list ... to be slow, compared to 'for

cheers, Bill

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900