c# - C#中字符串的快速哈希函数

标签 c# string performance hash

我想散列长度最大为 30 的字符串。如果时间紧迫,最好的办法是什么。该函数将被调用超过 1 亿次。目前我正在使用以下代码,

static UInt64 CalculateHash(string read, bool lowTolerance)
{
    UInt64 hashedValue = 0;
    int i = 0;
    while (i < read.Length)
    {
        hashedValue += read.ElementAt(i) * (UInt64)Math.Pow(31, i);
        if (lowTolerance) i += 2;
        else i++;
    }
    return hashedValue;
}

最佳答案

static UInt64 CalculateHash(string read)
{
    UInt64 hashedValue = 3074457345618258791ul;
    for(int i=0; i<read.Length; i++)
    {
        hashedValue += read[i];
        hashedValue *= 3074457345618258799ul;
    }
    return hashedValue;
}

这是 Knuth 哈希。您也可以使用 Jenkins

关于c# - C#中字符串的快速哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9545619/

相关文章:

c# - 当全局注册操作过滤器时跳过特定操作的过滤器

java - 我应该如何在java中实现子字符串函数?

java - 有没有办法在不使用 values/strings.xml 的情况下本地化 android 应用程序?

ios - 缓慢行为 pushPage Onsen UI

java - 当忙于旋转的Java线程绑定(bind)到物理内核时,是否会因为到达代码中的新分支而发生上下文切换?

c# - 如何将子类属性映射到每个层次结构的表中的列?

c# - 在 asp.net 中读取隐藏的控件值

c# - System.Net.Sockets.SocketException

从字符串中删除 HTML 标记的 Python 代码

javascript - 浏览器性能不佳,无法隐藏大型(>1000 行,20 列)表