Tija
Tija

Reputation: 1737

linq vs ToDictionary() and TryGetValue() - what is more efficient?

What is more efficient between these two approaches

object foundItem = (from m in myList where m.ID == id select m).FirstOrDefault();

or

Dictionary<string, object> dict = myList.ToDictionary(m => m.ID, m => m);
dict.TryGetValue(id, out foundItem);

Upvotes: 3

Views: 2161

Answers (4)

drowned
drowned

Reputation: 550

In addition to what's been pointed out already, these two code blocks don't exactly do the same thing. In the first example, 'found' will be an IEnumerable, in the second it will be a bool and foundItem will be whatever was stored in myList.

Upvotes: 2

Pleun
Pleun

Reputation: 8920

Well, I use the second approach when I have a large list and a lot of TryGetValues.

My experience is that in those conditions this is magnitudes faster.

The first is faster for a single lookup.

I have never used a stopwatch or anything like that to prove it so I cannot tell you where the break even point is.

Upvotes: 0

Aducci
Aducci

Reputation: 26664

I would guess that your first one would be fastest, because it mosty likely doesn't have to iterate through your whole list. I would modify it slightly to look more like this:

object found = myList.FirstOrDefault(m => m.ID == id);

Upvotes: 1

Daniel Earwicker
Daniel Earwicker

Reputation: 116674

If you're just doing one lookup, the non-dictionary one is faster because it avoids the overhead of building the dictionary.

If you're going to do a lot of lookups on the same dataset, the dictionary one is faster because it is a data structure specifically design for fast look up by a single key. The more lookups you do, the more it is worth the overhead of building the dictionary.

Upvotes: 5

Related Questions