Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using linq in this situation overkill

Tags:

c#

linq

I am thinking about a re-factor, but I don't know if the end result is just overkill. Currently I have

    IList<myobjecttypebase> m_items;

   public int GetIncrementTotal()
   {
     int incrementTot;
     foreach(myobjecttypebase x in m_items)
     { incrementTot += x.GetIncrement(); }
   }

Would it be overkill and/or less efficient to use linq for the ForEach

m_items.ToList().ForEach(x => incrementTot += x.GetIncrement());

Would the cast be a significant overhead here?

like image 990
Andrew Avatar asked Feb 03 '10 10:02

Andrew


3 Answers

Why not use the SUM operator directly on the IList?

It does have several overloads using Func delegates:

m_items.Sum(x => x.GetIncrement());
like image 58
Oded Avatar answered Oct 12 '22 19:10

Oded


The ToList method is an extension method used with LINQ, but the ForEach method is just a method in the List class.

The major overhead here is the call to the ToList method, which creates a new List from the collection. The ForEach also has a slight overhead as it has to call a delegate for each item.

If you want to use LINQ methods, the Aggregate method seems more appropriate:

public int GetIncrementTotal() {
  return m_items.Aggregate(0, (t, i) => t + i.GetIncrement());
}

Or Sum:

public int GetIncrementTotal() {
  return m_items.Sum(i => i.GetIncrement());
}

Either has a slight overhead over your original version, so if you want the most efficient, just stick to a simple loop.

like image 44
Guffa Avatar answered Oct 12 '22 17:10

Guffa


The overhead will be in iterating the collection twice.

m_items.ToList() // First iteration to add to the list all the items
   .ForEach(x => incrementTot += x.GetIncrement()); /* Second iteration to
                                                       perform logic */

ToList doesn't perform the iteration in lazy manner as most LINQ statements, therefor it will force the code iterate over the collection twice.

In general the LINQ form seems nicer to read, but if you're worrying about performance you better avoid it.

like image 40
Elisha Avatar answered Oct 12 '22 18:10

Elisha