Difference between Lookup() and Dictionary(Of list())

前端 未结 6 1386
暖寄归人
暖寄归人 2020-11-27 10:56

I\'m trying to wrap my head around which data structures are the most efficient and when / where to use which ones.

Now, it could be that I simply just don\'t unders

6条回答
  •  粉色の甜心
    2020-11-27 11:18

    When exception is not a option, go for Lookup

    If you are trying to get a structure as efficient as a Dictionary but you dont know for sure there is no duplicate key in input, Lookup is safer.

    As mentioned in another answer, it also supports null keys, and returns always a valid result when queried with arbitrary data, so it appears as more resilient to unknown input (less prone than Dictionary to raise exceptions).

    And it is especially true if you compare it to the System.Linq.Enumerable.ToDictionary function :

    // won't throw
    new[] { 1, 1 }.ToLookup(x => x); 
    
    // System.ArgumentException: An item with the same key has already been added.
    new[] { 1, 1 }.ToDictionary(x => x);
    

    The alternative would be to write your own duplicate key management code inside of a foreach loop.

    Performance considerations, Dictionary: a clear winner

    If you don't need a list and you are going to manage a huge number of items, Dictionary (or even your own custom tailored structure) would be more efficient:

            Stopwatch stopwatch = new Stopwatch();
            var list = new List();
            for (int i = 0; i < 5000000; ++i)
            {
                list.Add(i.ToString());
            }
            stopwatch.Start();
            var lookup = list.ToLookup(x => x);
            stopwatch.Stop();
            Console.WriteLine("Creation: " + stopwatch.Elapsed);
    
            // ... Same but for ToDictionary
            var lookup = list.ToDictionary(x => x);
            // ...
    

    As Lookup has to maintain a list of items for each key, it is slower than Dictionary (around 3x slower for huge number of items)

    Lookup speed: Creation: 00:00:01.5760444

    Dictionary speed: Creation: 00:00:00.4418833

提交回复
热议问题