Sunday, April 17, 2011

LINQ Optimization Question

So I've been using LINQ for a while, and I have a question.

I have a collection of objects. They fall into two categories based on their property values. I need to set a different property one way for one group, and one way for the other:

foreach(MyItem currentItem in myItemCollection)
{
    if (currentItem.myProp == "CATEGORY_ONE")
    {
        currentItem.value = 1;
    }
    else if (currentItem.myProp == "CATEGORY_TWO")
    {
         currentItem.value = 2;
    }
}

Alternately, I could do something like:

myItemCollection.Where(currentItem=>currentItem.myProp == "CATEGORY_ONE").ForEach(item=>item.value = 1);
myItemCollection.Where(currentItem=>currentItem.myProp == "CATEGORY_TWO").ForEach(item=>item.value = 2);

I would think the first one is faster, but figured it couldn't hurt to check.

From stackoverflow
  • Iterating through the collection only once (and not calling any delegates, and not using as many iterators) is likely to be slightly faster, but I very much doubt that it'll be significant.

    Write the most readable code which does the job, and only worry about performance at the micro level (i.e. where it's easy to change) when it's a problem.

    I think the first piece of code is more readable in this case. Less LINQy, but more readable.

  • How about doing it like that?

    myItemCollection.ForEach(item => item.value = item.myProp == "CATEGORY_ONE" ? 1 : 2);
    
    Oscar Cabrero : i think this one will perform sligthy faster than the first one since it only evaulates one condition +1
    Samuel : -1 because it doesn't capture what the foreach does. There are two ifs, not an if and an else.
  • Real Answer

    Only a profiler will really tell you which one is faster.

    Fuzzy Answer

    The first one is most likely faster in terms of raw speed. There are two reasons why

    1. The list is only iterated a single time
    2. The second one erquires 2 delegate invocations for every element in the list.

    The real question though is "does the speed difference between the two solutions matter?" That is the only question that is relevant to your application. And only profiling can really give you much data on this.

0 comments:

Post a Comment