Skip to content

[API Proposal]: string.GetHashCodeNonRandomized #77679

Description

@stephentoub

Background and motivation

In .NET Core, string hash codes are always randomized. This is critical to avoid certain kinds of attacks when adding arbitrary, untrusted inputs into types like Dictionary<,> and HashSet<>. However, for situations where the inputs are trusted, the overhead of these randomized hash codes makes them measurably more expensive than their non-randomized counterparts. As such, Dictionary<,> and HashSet<> both start out with non-randomized hash codes and only upgrade to randomized ones when enough collisions are detected. Such a capability is valuable for other collection types as well, but the raw primitives (the non-randomized hash code implementations) aren't trivial to implement efficiently and aren't exposed.

API Proposal

namespace System
{
    public sealed class String
    {
        public static int GetHashCode(ReadOnlySpan<char> value);
        public static int GetHashCode(ReadOnlySpan<char> value, StringComparison comparisonType);

+       public static int GetHashCodeNonRandomized(ReadOnlySpan<char> value);
+       public static int GetHashCodeNonRandomized(ReadOnlySpan<char> value, StringComparison comparisonType);
    }
}

API Usage

int hashcode = string.GetHashCodeNonRandomized(value, StringComparison.OrdinalIgnoreCase);

Alternative Designs

We could instead or in addition expose StringComparer singletons:

namespace System
{
    public abstract class StringComparer
    {
        public static StringComparer Ordinal { get; }
        public static StringComparer OrdinalIgnoreCase { get; }

+       public static StringComparer OrdinalNonRandomized { get; }
+       public static StringComparer OrdinalIgnoreCaseNonRandomized { get; }
    }
}

If we did that instead of the proposed APIs, we should also consider adding Equals/GetHashCode overloads for ReadOnlySpan<char> to StringComparer (something we might want to do anyway as part of #27229).

Risks

A risk could be developers defaulting to using these instead of the randomized implementations in situations where the randomized implementations are warranted. However, some developers are already writing their own hash implementations to avoid the randomized overhead, and their implementations may be worse or less efficient than what's already in the box.

Activity

  1. added
    api-suggestion
    on Oct 31, 2022
  2. added this to the 8.0.0 milestone on Oct 31, 2022
  3. stephentoub commented on Oct 31, 2022

    @stephentoub
    MemberAuthor
  4. bartonjs commented on Oct 31, 2022

    @bartonjs
    Member

    I'd rather see it as new StringComparers. It doesn't seem to me to be a universal enough need on every String to be worthy of an instance method.

  5. stephentoub commented on Oct 31, 2022

    @stephentoub
    MemberAuthor

    It doesn't seem to me to be a universal enough need on every String to be worthy of an instance method.

    The proposal has them as a static methods, not instance.

    (Also as noted, we'd need support for ReadOnlySpan<char> inputs, so as just a StringComparer, we'd need to either augment StringComparer to also supports spans, or expose separate span-based methods as well.)

  6. Nuklon commented on Nov 1, 2022

    @Nuklon

    GetNonRandomizedHashCode instead? GetHashCodeNonRandomized is some odd English.

  7. GSPP commented on Nov 2, 2022

    @GSPP

    From reading the source code, it seems that the randomized comparer calls an entirely different algorithm. Can you educate me on why that is? Why does it not call the same algorithm just with a different seed?

    public override int GetHashCode(string? obj)
    {
    if (obj is null)
    {
    return 0;
    }
    // The Ordinal version of Marvin32 operates over bytes.
    // The multiplication from # chars -> # bytes will never integer overflow.
    return Marvin.ComputeHash32(
    ref Unsafe.As<char, byte>(ref obj.GetRawStringData()),
    (uint)obj.Length * 2,
    _seed.p0, _seed.p1);
    }
    }

    public virtual int GetHashCode(string? obj)
    {
    // This instance may have been deserialized into a class that doesn't guarantee
    // these parameters are non-null. Can't short-circuit the null checks.
    return obj?.GetNonRandomizedHashCode() ?? 0;
    }

    internal unsafe int GetNonRandomizedHashCode()
    {
    fixed (char* src = &_firstChar)
    {
    Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
    Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary");
    uint hash1 = (5381 << 16) + 5381;
    uint hash2 = hash1;
    uint* ptr = (uint*)src;
    int length = this.Length;
    while (length > 2)
    {
    length -= 4;
    // Where length is 4n-1 (e.g. 3,7,11,15,19) this additionally consumes the null terminator
    hash1 = (BitOperations.RotateLeft(hash1, 5) + hash1) ^ ptr[0];
    hash2 = (BitOperations.RotateLeft(hash2, 5) + hash2) ^ ptr[1];
    ptr += 2;
    }
    if (length > 0)
    {
    // Where length is 4n-3 (e.g. 1,5,9,13,17) this additionally consumes the null terminator
    hash2 = (BitOperations.RotateLeft(hash2, 5) + hash2) ^ ptr[0];
    }
    return (int)(hash1 + (hash2 * 1566083941));
    }
    }


    It seems that the non-randomized version is not seeded at all and will therefore result in the same output across process restarts. This could lead people to take a dependency on the concrete algorithm (although they should not be doing that). This could be avoided by xoring the result with a per-process constant. The performance cost of that should be very small.

  8. EgorBo commented on Nov 2, 2022

    @EgorBo
    Member

    It seems that the non-randomized version is not seeded at all and will therefore result in the same output across process restarts. This could be avoided by xoring the result with a per-process constant. The performance cost of that should be very small.

    Isn't that why it's called "NonRandomized" ? 🙂

    From reading the source code, it seems that the randomized comparer calls an entirely different algorithm. Can you educate me on why that is?

    See "Background and motivation" section of this proposal, Marvin32 hash code is good, but it's obviously slower than a simpler non-randomized implementation.

  9. ArminShoeibi commented on Nov 30, 2022

    @ArminShoeibi
    Contributor

    GetNonRandomizedHashCode instead? GetHashCodeNonRandomized is some odd English.

    @Nuklon I think it's better this way GetHashCodeNonRandomized because of Intellisense and ordering.

  10. En3Tho commented on Nov 30, 2022

    @En3Tho
    Contributor

    Personally I would vote for option 2 - a new comparer as on String class it feels like it's kinda leaking implementation details. String methods are usually "generic" like Contains, StartsWith etc. And this one is just way to specific to be on String class. Also, I wouldn't personally want newcomers to find this faster than they should :) This kind of thing is more or less oriented on library authors I guess.

  11. self-assigned this
    on Mar 3, 2023
  12. modified the milestones: 8.0.0, Future on Apr 23, 2023
  13. 10 remaining items

  14. added
    api-ready-for-review
    and removed
    api-suggestion
    on Dec 12, 2025
  15. bartonjs commented on Sep 29, 2026

    @bartonjs
    Member

    Video

    • "NonRandomized" doesn't say "stable", but almost implies it. The best alternative we came up with was "Weak".
      • To help avoid the notion that it's stable, let's give it a per-process random seed still, but using a simple operation like XOR.
    • The name "Weak" doesn't pair well with the StringComparer objects, so we'll leave those out and just have the primitive.
    • string seems the best location for these, given the static string.GetHashCode(ROSpan) APIs
    namespace System
    {
        public sealed class String
        {
            public static int GetHashCodeWeak(ReadOnlySpan<char> value);
    
            // Only Ordinal and OrdinalIgnoreCase in v1, we could all others later.
            public static int GetHashCodeWeak(ReadOnlySpan<char> value, StringComparison comparisonType);
        }
    }
  16. added
    api-approved
    and removed
    api-ready-for-review
    on Sep 29, 2026
  17. ladeak commented on Sep 29, 2026

    @ladeak
    Contributor

    How can I use this API? Is it only useful when creating a custom dictionary/set collection, or are there other use-cases? When reading this: #68616 - when should I use this over xxHash?

  18. EgorBo commented on Sep 29, 2026

    @EgorBo
    Member

    How can I use this API? Is it only useful when creating a custom dictionary/set collection, or are there other use-cases? When reading this: #68616 - when should I use this over xxHash?

    xxHash doesn't have an IgnoreCase hash, does it?

  19. bartonjs commented on Sep 29, 2026

    @bartonjs
    Member

    when should I use this over xxHash?

    When you want something faster than Marvin, don't care much about hash collisions, don't care what the algorithm is, and don't need the value to be stable across processes.

    And, as @EgorBo says, when you want an easy way of doing the above with IgnoreCase 😄.

  20. Charlieface commented on Sep 30, 2026

    @Charlieface

    when should I use this over xxHash?

    When you want something faster than Marvin, don't care much about hash collisions, don't care what the algorithm is, and don't need the value to be stable across processes.

    And, as @EgorBo says, when you want an easy way of doing the above with IgnoreCase 😄.

    So what would be the recommended way of having a case-insensitive fast hashing algorithm that is stable across processes? I have an exact need for this kind of thing: I need to hash some text so I can quickly compare against stored hash values, I don't care that much about hash collisions and I need it to be stable. There seems to be no recommended way of doing this at the moment.

  21. EgorBo commented on Sep 30, 2026

    @EgorBo
    Member

    when should I use this over xxHash?

    When you want something faster than Marvin, don't care much about hash collisions, don't care what the algorithm is, and don't need the value to be stable across processes.
    And, as @EgorBo says, when you want an easy way of doing the above with IgnoreCase 😄.

    So what would be the recommended way of having a case-insensitive fast hashing algorithm that is stable across processes? I have an exact need for this kind of thing: I need to hash some text so I can quickly compare against stored hash values, I don't care that much about hash collisions and I need it to be stable. There seems to be no recommended way of doing this at the moment.

    I think you have no other choice but to change the casing of your input first, then use any stable/known hashing without randomization

  22. Manish-1kumar commented on Nov 17, 2026

    @Manish-1kumar
    Contributor

    Hi @bartonjs, @stephentoub,

    I would like to contribute the implementation for this approved API proposal.

    Proposed Plan

    1. Expose the approved overloads on System.String:
      • public static int GetHashCodeWeak(ReadOnlySpan<char> value)
      • public static int GetHashCodeWeak(ReadOnlySpan<char> value, StringComparison comparisonType)
    2. Route Ordinal to string.GetNonRandomizedHashCode(value) and OrdinalIgnoreCase to string.GetNonRandomizedHashCodeOrdinalIgnoreCase(value).
    3. Throw ArgumentException with ExceptionResource.NotSupported_StringComparison for all other StringComparison modes as determined in the API review.
    4. Update System.Runtime.ref and add comprehensive unit tests in System.Runtime.Tests covering determinism, span conversions, and exception semantics.

    I have verified the implementation and tests locally (all CoreLib, ref, and test targets build clean). May I go ahead and open a PR for this?

  23. bartonjs commented on Nov 17, 2026

    @bartonjs
    Member

    @Manish-1kumar The issue is now assigned to you, PR at your leisure 😄

  24. Manish-1kumar commented on Nov 18, 2026

    @Manish-1kumar
    Contributor

    Thanks @bartonjs! Opened #137828. Per the API review notes, the result is XOR'ed with a per-process random seed (separate from the Marvin seed), so it isn't mistaken for a stable hash.

  25. added
    in-pr
    on Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.Runtimein-pr

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions