Best hashing algorithm in terms of hash collisions and performance for strings

前端 未结 9 1184
忘掉有多难
忘掉有多难 2020-11-28 03:37

What would be the best hashing algorithm if we had the following priorities (in that order):

  1. Minimal hash collisions
  2. Performance

It doe

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 04:01

    The simple hashCode used by Java's String class might show a suitable algorithm.

    Below is the "GNU Classpath" implementation. (License: GPL)

      /**
       * Computes the hashcode for this String. This is done with int arithmetic,
       * where ** represents exponentiation, by this formula:
    * s[0]*31**(n-1) + s[1]*31**(n-2) + ... + s[n-1]. * * @return hashcode value of this String */ public int hashCode() { if (cachedHashCode != 0) return cachedHashCode; // Compute the hash code using a local variable to be reentrant. int hashCode = 0; int limit = count + offset; for (int i = offset; i < limit; i++) hashCode = hashCode * 31 + value[i]; return cachedHashCode = hashCode; }

提交回复
热议问题