开发者

Linq method body Best Practice question

开发者 https://www.devze.com 2022-12-23 03:18 出处:网络
Which of these two statements is faster/better practice? myList.Where(x => { bool itemOne= x.ItemOne == paramItemOne;

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?


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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消