Which is faster, String or Integer as hashkey in Java?

Integer will perform better than String. Following is code for the hashcode computation for both.

Integer hash code implementation

/**
     * 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;
    }

String hash code implementation

 /**
     * 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;
    }

If you have performance problem, it's quite unlikely that the issue is due to the HashMap/HashTable. While hashing string is slightly more expensive than hashing integers, it's rather small difference, and hashCode is cached so it's not recalculated if you use the same string object, you are unlikely to get any significant performance benefit from converting it first to integer.

It's probably more fruitful to look somewhere else for the source of your performance issue. Have you tried profiling your code yet?

Tags:

Java

Hashtable