java - 哪个更快,String 或 Integer 作为 Java 中的 hashkey?

标签 java hashtable

我正在处理一个问题,我遇到执行时间变得过长的问题,现在我正在寻找可能的优化。

问题:使用 String 或 Integer 作为 haskey 在性能上是否有任何(相当大的)差异?

问题是我有一个图,其中的节点存储在以字符串为键的哈希表中。例如,键如下 - “0011”或“1011”等。现在我也可以将它们转换为整数,如果这意味着可以缩短执行时间的话。

最佳答案

Integer 比 String 表现更好。以下是两者的哈希码计算代码。

整数哈希码实现

/**
     * Returns a hash code for this <code>Integer</code>.
     *
     * @return  a hash code value for this object, equal to the 
     *          primitive <code>int</code> value represented by this 
     *          <code>Integer</code> object. 
     */
    public int hashCode() {
    return value;
    }

字符串哈希码实现

 /**
     * Returns a hash code for this string. The hash code for a
     * <code>String</code> object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using <code>int</code> arithmetic, where <code>s[i]</code> is the
     * <i>i</i>th character of the string, <code>n</code> is the length of
     * the string, and <code>^</code> indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    public int hashCode() {
    int h = hash;
    if (h == 0) {
        int off = offset;
        char val[] = value;
        int len = count;

            for (int i = 0; i < len; i++) {
                h = 31*h + val[off++];
            }
            hash = h;
        }
        return h;
    }

关于java - 哪个更快,String 或 Integer 作为 Java 中的 hashkey?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15632300/

相关文章:

java - 在没有线程阻塞的情况下回调到主线程(Java)

java - 搜索算法如何处理 Java 集合(例如 HashSet)中的对象?

java - 从 .data 文件读取到 Java - 如何将信息存储在数组数组中?

.net - 对哈希表进行排序的原因

hashtable - Freemarker Hashtable<Integer, String>,按键迭代

java: map 动物园,选择什么

java - 尽管默认情况下应该启用异步支持,但未启用异步支持

java - Java 中的 Volatile 关键字

java - Java中最多可以处理N个元素的数组?

java - 如何以排序的方式检索文档的值?