score:2

Accepted answer

If I'm not mistaken, in terms of big O efficiency, it's the same. It's just an extra method call.

Regarding the second question,

var xmlElem = (from n in xDocument.Descendants() where (string)n.Attribute("name") == "some_node_name" select n).SingleOrDefault();

can be expressed more simply as

var xmlElem = xDocument.Descendants().SingleOrDefault(n => (string)n.Attribute("name") == "some_node_name");

score:0

(CheckBox)lstControls.Where(x => x.ID == "some_id").SingleOrDefault();

This must test every item in the enumeration.

(CheckBox)lstControls.SingleOrDefault(x => x.ID == "some_id");

This can stop testing items and return as soon as it finds something.

If you have a very large enumeration, and an item near the front satisfies the condition, then the former may be significantly faster. In the case where the number of items satisfying the condition increases with the size of the enumeration, the speedup may be asymptotic. For instance, if one out of every k items on average satisfies the condition, then the average run time of the second snippet is constant.


Related Articles