tags:

views:

79

answers:

4

Which of these two statements is faster/better practice?

myList.Where(x =>
            {
                bool itemOne= x.ItemOne == paramItemOne;
                bool itemTwo = x.ItemTwo == paramItemTwo;
                return itemOne && itemTwo;
            })


myList.Where(x => x.ItemOne == paramItemOne).Where(x=>x.ItemTwo == paramItemTwo)

or are they the same?

+7  A: 

I'd say neither. The fastest is going to be:

myList.Where(x => x.ItemOne == paramItemOne && x.ItemTwo == paramItemTwo)

(assuming the compiler/JIT doesn't optimize away the variable assignments in your 1st form)

The second form will be slower because it may involve significantly more method invocation on the delegates supplied to the Where statements.

spender
The compiler cannot optimize out the second boolean in the first form - it would remove side effects.
SLaks
A: 

The performance would be either the same or very close. The second one might have more method overhead.

More important than performance, I would say the first one is better practice because it is much more clear.

Patrick Karcher
+1  A: 

Results are the same, however, I'd recommend you to write this instead:

myList.Where(x =>
            {
                return x.ItemOne == paramItemOne && x.ItemTwo == paramItemTwo;
            });

This is guaranteed to work faster, because now x.ItemTwo == paramItemTwo won't be even calculated if x.ItemOne == paramItemOne

portland
Um... both conditions must be satified, so your final assertion doesn't hold. Both predicates must be evaluated for AND to evaluate to true. However, in the case that x.ItemOne != paramItemOne, the second predicate will not be evaluated, but this also holds true for the Where().Where() form, as items filtered by the first Where statement will not be part of the enumerable against which the second Where executes.
spender
A: 

The first check both conditions onse per list item. The second filters by the first condition and then filters the result by the second condition.

The second is creating and populating another temp collection but makes less comparing for the second condition.

tsinik