I have a ILookup<TKey,TElement> lookup
from which I fairly often get elements and iterate trough them using LINQ or foreach
. I look up like this IEnumerable<TElement> results = lookup[key];
.
Thus, results
needs to be enumerated at least once every time I use lookup results (and even more if I'm iterating multiple times if I don't use .ToList() first).
Even though its not as "clean", wouldn't it be better (performance-wise) to use a Dictionary<TKey,List<TElement>>
, so that all results from a key are only enumerated on construction of the dictionary? Just how taxing is ToList()?
ToLookup
, like all the other ToXXX
LINQ methods, uses immediate execution. The resulting object has no reference to the original source. It effectively does build a Dictionary<TKey, List<TElement>>
- not those exact types, perhaps, but equivalent to it.
Note that there's a difference though, which may or may not be useful to you - the indexer for a lookup returns an empty sequence if you give it a key which doesn't exist, rather than throwing an exception. That can make life much easier if you want to be able to just index it by any key and iterate over the corresponding values.
Also note that although it's not explicitly documented, the implementation used for the value sequences does implement ICollection<T>
, so calling the LINQ Count()
method is O(1) - it doesn't need to iterate over all the elements.
See my Edulinq post on ToLookup
for more details.
Assuming the implementation is System.Linq.Lookup
(does ILookup
have any other implementations?), the elements presented in lookup[key]
are stored in an array of elements as a field of System.Linq.Lookup.Grouping
. Repeatedly looking them up won't cause a re-iteration of source. Of course, rebuilding the Lookup
will be more costly, but once built, the source is no longer accessed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With