Skip to content

LINQ uses a different hashing implementation from Dictionary<TKey, TValue> #128583

Closed as not planned

Description

@tannergooding

!NOTE: This was reported via the feedback tool and was hand ported to GitHub

Summary

The System.Linq library differs in its internal hash table implementation (System.Linq.Lookup&lt;TKey, TElement&gt;), which is used by GroupBy, ToLookup, Join, and GroupJoin.

This can create different worst case pessimizations as compared to other dictionary like scenarios and doesn't contain the same fallback handling for cases like strings that can have higher chance of collision; for example Dictionary<TKey, TValue> will change to a more expensive hashing algorithm in such a scenario.

It would be beneficial to unify these implementations so that devs can rely on the behavior and perf characteristics regardless of what APIs they use in .NET

Repro

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

class Program
{
    static void Main(string[] args)
    {
        int N = 200000;

        Console.WriteLine($"Testing with N={N}");
        Console.WriteLine();

        int M = 262143;

        var randomData = Enumerable.Range(0, N).Select(i => (long)i).ToArray();
        Random.Shared.Shuffle(randomData);

        var collisionData = new long[N];
        int found = 0;

        for (int h = 0; found < N; h++)
        {
            for (long t = 0; t < int.MaxValue; t += M)
            {
                long l = (t ^ h) & 0xFFFFFFFFL;
                long val = (l) | ((long)h << 32);

                if ((val.GetHashCode() & 0x7FFFFFFF) % M == 0)
                {
                    collisionData[found++] = val;
                    if (found >= N) break;
                }
            }
        }

        var customComparer = new CustomEqualityComparer();

        Console.WriteLine("GroupBy (Lookup):");
        var sw = Stopwatch.StartNew();
        var res1 = randomData.GroupBy(x => x).Count();
        sw.Stop();
        Console.WriteLine($"    Random: {sw.ElapsedMilliseconds} ms");

        sw.Restart();
        var res1A = randomData.GroupBy(x => x, customComparer).Count();
        sw.Stop();
        Console.WriteLine($"    Random (custom comparer): {sw.ElapsedMilliseconds} ms");

        sw.Restart();
        var res2 = collisionData.GroupBy(x => x).Count();
        sw.Stop();
        Console.WriteLine($"    Collision: {sw.ElapsedMilliseconds} ms");

        sw.Restart();
        var res2A = collisionData.GroupBy(x => x, customComparer).Count();
        sw.Stop();
        Console.WriteLine($"    Collision (custom comparer): {sw.ElapsedMilliseconds} ms");

        Console.WriteLine("\nToDictionary:");
        sw.Restart();
        var dict1 = randomData.ToDictionary(x => x);
        sw.Stop();
        Console.WriteLine($"    Random: {sw.ElapsedMilliseconds} ms");

        sw.Restart();
        var dict1A = randomData.ToDictionary(x => x, customComparer);
        sw.Stop();
        Console.WriteLine($"    Random (custom comparer): {sw.ElapsedMilliseconds} ms");

        sw.Restart();
        var dict2 = collisionData.ToDictionary(x => x);
        sw.Stop();
        Console.WriteLine($"    Collision: {sw.ElapsedMilliseconds} ms");

        sw.Restart();
        var dict2A = collisionData.ToDictionary(x => x, customComparer);
        sw.Stop();
        Console.WriteLine($"    Collision (custom comparer): {sw.ElapsedMilliseconds} ms");

        Console.WriteLine("\nDistinct (HashSet):");
        sw.Restart();
        var dist1 = randomData.Distinct().Count();
        sw.Stop();
        Console.WriteLine($"    Random: {sw.ElapsedMilliseconds} ms");

        sw.Restart();
        var dist1A = randomData.Distinct(customComparer).Count();
        sw.Stop();
        Console.WriteLine($"    Random (custom comparer): {sw.ElapsedMilliseconds} ms");

        sw.Restart();
        var dist2 = collisionData.Distinct().Count();
        sw.Stop();
        Console.WriteLine($"    Collision: {sw.ElapsedMilliseconds} ms");

        sw.Restart();
        var dist2A = collisionData.Distinct(customComparer).Count();
        sw.Stop();
        Console.WriteLine($"    Collision (custom comparer): {sw.ElapsedMilliseconds} ms");
    }

    public sealed class CustomEqualityComparer : IEqualityComparer<long>
    {
        public bool Equals(long x, long y)
        {
            return x == y;
        }

        public int GetHashCode([DisallowNull] long obj)
        {
            return 0;
        }
    }
}

Output

Testing with N=200000

GroupBy (Lookup):
    Random: 47 ms
    Random (custom comparer): 58131 ms
    Collision: 22427 ms
    Collision (custom comparer): 70755 ms

ToDictionary:
    Random: 8 ms
    Random (custom comparer): 69294 ms
    Collision: 8 ms
    Collision (custom comparer): 69293 ms

Distinct (HashSet):
    Random: 6 ms
    Random (custom comparer): 69191 ms
    Collision: 11 ms
    Collision (custom comparer): 69228 ms

Activity

  1. added
    tenet-performance
    untriaged
    Priority:3
    on May 26, 2026
  2. dotnet-policy-service commented on May 26, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-collections
    See info in area-owners.md if you want to be subscribed.

  3. tannergooding commented on May 26, 2026

    @tannergooding
    MemberAuthor

    As shown in the repro, this isn't really a bug or anything of the like. You can hit the "worst case" scenarios even in Dictionary<TKey, TValue> by intentionally colliding keys (and so can risk such a scenario with random data if the keys do collide).

    However, the hash table implementation used by Lookup isn't as "robust" and so can pessimize for hash codes that don't pessimize with Dictionary, making it difficult to choose a single hashing algorithm that works optimally everywhere.

    Unifying the implementations allows users to do handle this reliably.

  4. eiriktsarpalis commented on May 27, 2026

    @eiriktsarpalis
    Member

    These are not identical implementations though. Lookup for example does handle null keys whereas dictionary does not.

  5. tannergooding commented on May 29, 2026

    @tannergooding
    MemberAuthor

    Yes, but that's largely irrelevant to the algorithm and data structures used here. It mostly just makes a difference to a pre-condition on entries added.

  6. eiriktsarpalis commented on May 29, 2026

    @eiriktsarpalis
    Member

    I'm just pointing out it's not as straightforward as replacing one implementation with the other. We'd probably need to wrap keys that are admit null.

    In any case, seems like a good refactoring scenario for copilot to explore.

  7. eiriktsarpalis commented on Jun 24, 2026

    @eiriktsarpalis
    Member

    Closing as wontfix per feedback in the prototype PR.

  8. removed
    untriaged
    on Jun 24, 2026
  9. locked and limited conversation to collaborators on Jul 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Priority:3area-System.Collectionstenet-performance

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions