简体   繁体   中英

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);

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.

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.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM