让我先说这可能是不值得做的 - 你的散列函数不太可能成为你程序中的瓶颈,所以使散列函数更加精细以提高它的效率可能会只是让它更难以理解和维护,而不会使您的计划更快地实现。所以不要这样做,除非你确定你的程序花费了很大一部分时间来计算字符串散列,并且确保你有一个很好的基准例程,你可以在这个变化的“之前”和“之后”运行来验证它确实可以显着加快速度,否则你可能只是在追逐彩虹。
也就是说,哈希长字符串更加迅速将处理串在一个时间一个字,而不是一次一个字符,像这样一个可能的方式:
unsigned int aSlightlyFasterHash(const string & s)
{
const unsigned int numWordsInString = s.size()/sizeof(unsigned int);
const unsigned int numExtraBytesInString = s.size()%sizeof(unsigned int);
// Compute the bulk of the hash by reading the string a word at a time
unsigned int hash = 0;
const unsigned int * iptr = reinterpret_cast<const unsigned int *>(s.c_str());
for (unsigned int i=0; i<numWordsInString; i++)
{
hash += *iptr;
iptr++;
}
// Then any "leftover" bytes at the end we will mix in to the hash the old way
const unsigned char * cptr = reinterpret_cast<const unsigned char *>(iptr);
unsigned int multiplier = 1;
for(unsigned int i=0; i<numExtraBytesInString; i++)
{
hash += (multiplier * *cptr);
cptr++;
multiplier *= 31;
}
return hash;
}
注意上面函数将返回不同于您提供的散列函数的散列值。
这由四个因素减少了循环迭代的次数;当然,这个功能的执行可能受到RAM带宽而不是CPU周期的限制,所以如果现代CPU的速度没有明显提高,那么就太惊讶了。如果RAM带宽确实是瓶颈,那么你可以做的事情不多,因为你必须读取字符串的内容才能计算字符串的散列码;除了预先计算哈希代码并将其存储在某个地方,但只有在您知道所有要提前使用的字符串的情况下才有效)。
如果你链接到一个实际的图像,链接到图像,而不是图库 –
也许代码审查是一个更好的论坛。 –
请注意,unsigned int不能保证完全是32位宽(尽管它通常很宽)。如果您想要依赖32位无符号变量的溢出行为,那么如果使用类型uint32_t(而不是无符号整数)代替(通过#include),代码将更具可移植性。 –