views:

261

answers:

3

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.

+4  A: 

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.

Jon Skeet
+3  A: 

How about doing it like that?

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

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.

JaredPar