Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Linq Faster, Slower or the same?

Is this:

Box boxToFind = AllBoxes.FirstOrDefault(box => box.BoxNumber == boxToMatchTo.BagNumber);

Faster or slower than this:

Box boxToFind ;
foreach (Box box in AllBoxes)
{
    if (box.BoxNumber == boxToMatchTo.BoxNumber)
    {
        boxToFind = box;
    }
}

Both give me the result I am looking for (boxToFind). This is going to run on a mobile device that I need to be performance conscientious of.

like image 581
Vaccano Avatar asked May 21 '10 17:05

Vaccano


1 Answers

It should be about the same, except that you need to call First (or, to match your code, Last), not Where.
Calling Where will give you a set of matching items (an IEnumerable<Box>); you only want one matching item.

In general, when using LINQ, you need to be aware of deferred execution. In your particular case, it's irrelevant, since you're getting a single item.

like image 193
SLaks Avatar answered Sep 27 '22 20:09

SLaks