views:

275

answers:

6

Is this:

Box boxToFind = AllBoxes.Where(box => box.BoxNumber == boxToMatchTo.BagNumber);
EDIT:

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.

+3  A: 

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.

SLaks
FirstOrDefault to avoid exceptions
hunter
@hunter: Unless he wants an exception.
SLaks
+1  A: 

If micro-optimization is your thing, LINQ performs worse, this is just one article, there are a lot of other posts you can find.

RandomNoob
**Pre-mature optimization is the root of all evil.** This is highly unlikely to be relevant to him.
SLaks
Don't know if you read the comments for that article, but the bulk of the problem wasn't the iteration but the implicit cast in his original code. Anders Hejlsberg pointed out that a query that didn't involve per-iteration cast operations was reasonably close to the for loop.
Mike Burton
A: 

The fastest is when you are using for loop. But the difference is so small that you are ignore it. It will only matter if you are building a real-time application but then for those applications maybe C# is not the best choice anyway!

azamsharp
+7  A: 

The difference is not important unless you've identified that this particular loop as a performance bottleneck through profiling.

If profiling does find it to be a problem, then you'll want to look into alternate storage. Store the data in a dictionary which provides faster lookup than looping through an array.

Sam
A dictionary provides faster lookup than an array? It sure as hell does not. Dictionaries are backed by arrays, with additional calculations each time you access an element. Therefore, it's impossible for a dictionary to be faster than an array in an iteration.
Rubys
@Rubys - Dictionary lookups are O(1), iterating through an array is O(n) so Dictionary lookups are faster for a large enough collection (assuming a sensible hash function).
Lee
@Rubys, Dictionary's are backed by an array of arrays. A hashcode is used to identify exactly which element in the first array to retrieve. There is no loop, just a simple mathematical calculation. That gives you the second array, often referred to as the bucket. Then the code loops through the bucket to find the exact item. A good collection size and hash code will result in buckets that have only a few items. The end result is that the dictionary is significantly faster than an array loop.
Sam
@Rubys: I think you're a little mixed up. Accessing an item at a known index in an array is as fast as it gets, yes. *Enumerating* over an array to *find* that index is *not* fast. A dictionary works by exploiting a hash function to attempt to bypass the slow part (enumerating) and jump straight to the fast part (access by index).
Dan Tao
Two options: I misunderstood, or you misunderstood. You are three, so I"m inclined to think it's the former. How is enumerating over an entire dictionary faster than enumerating over an entire array? Lookups are faster on dictionary if you don't know the location of the item, but he may have simplified the example quite a bit, and in the actual method you have to preform some sort of calculation, or it could be anything. The form it's in right now, sure, dictionary, but It's not always possible
Rubys
@Rubys, Dan Tao is saying something different. He's comparing simple lookup in an array vs loopkup in a dictionary. Yes, in that case an array is faster. The original post is talking about looping through an array to find an item vs lookup in a dictionary. In this case the dictionary is significantly faster unless the array is tiny or the hash code function sucks.
Sam
@Dan Tao, you're comparing array lookup vs dictionary lookup. We're talking about looping through an array to find an item vs dictionary lookup.
Sam
@Sam: I interpreted your answer to suggest, basically, considering the use of a dictionary with keys corresponding to the value being looked up (in the OP's case, `BagNumber`). I am indeed comparing looping through an array with dictionary lookup. It seemed to me Rubys interpreted your answer to be suggesting looping over a dictionary. I feel we are in agreement, except that perhaps I did not express myself clearly enough. Am I missing something here?
Dan Tao
@Dan Tao. I think we're in agreement. Direct lookup is faster in an array than a dictionary, but direct lookup in a dictionary is faster than looping over an array. As always, specific results can vary depending on exact data (size of array vs quality of hash code).
Sam
A: 

Micro optimization will kill you.
First, finish the whole class, then, if you have performance problems, run a profiler and check for the hotspots of the application.
Make sure you're using the best algorithms you can, then turn to micro optimizations like this.

In case you already did and I'm just being an asshole:
Slow -> Fast
LINQ < foreach < for < unsafe for (The last option is not recommended).
Abstractions will make your code slower, 95% of the time.

Rubys
A: 

If AllBoxes is an IQueryable, it can be faster than the loop, because the queryable could have an optimized implementation of the Where-operation (for example an indexed access).

Rauhotz
@Sam: IQueryable inherits IEnumerable, so a foreach loop works
Rauhotz