在Java中,字符串或整数作为哈希键,哪个更快?
我正在解决一个问题,我有执行时间变得太大的问题,现在我正在寻找可能的优化 问题:使用字符串或整数作为haskey在性能上是否有(相当大的)差异在Java中,字符串或整数作为哈希键,哪个更快?,java,hashtable,Java,Hashtable,我正在解决一个问题,我有执行时间变得太大的问题,现在我正在寻找可能的优化 问题:使用字符串或整数作为haskey在性能上是否有(相当大的)差异 问题是我有一个节点存储在哈希表中的图,其中字符串是键。例如,键如下所示——“0011”或“1011”等。现在,如果这意味着执行时间的改进,我也可以将它们转换为整数 整数将比字符串执行得更好。下面是这两种方法的hashcode计算代码 整数散列码实现 /** * Returns a hash code for this <code>I
问题是我有一个节点存储在哈希表中的图,其中字符串是键。例如,键如下所示——“0011”或“1011”等。现在,如果这意味着执行时间的改进,我也可以将它们转换为整数 整数将比字符串执行得更好。下面是这两种方法的hashcode计算代码 整数散列码实现
/**
* 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;
}
字符串哈希代码实现
/**
* 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;
}
*使用int
算术,其中s[i]
是
*字符串的第i个字符,n
是
*字符串,而^
表示幂运算。
*(空字符串的哈希值为零。)
*
*@返回此对象的哈希代码值。
*/
公共int hashCode(){
int h=散列;
如果(h==0){
int off=偏移量;
char val[]=值;
int len=计数;
对于(int i=0;i例如,看看你是否想做一些适当的微基准测试。还有许多其他资源可用于分析等 如果您有性能问题,那么问题不大可能是由于HashMap/HashTable引起的。虽然哈希字符串比哈希整数稍微贵一点,但差别很小,而且哈希代码是缓存的,所以如果使用同一个字符串对象,就不会重新计算它,但将其首先转换为整数不太可能获得任何显著的性能好处
在其他地方寻找性能问题的根源可能会更有成效。你试过分析你的代码了吗?String的hashcode是缓存的,所以不会有太大的区别。问题可能在其他地方。。。您应该分析代码以找到瓶颈。注意:在单线程情况下,HashMap的性能会比Hashtable稍好一些。我建议您分析一下您的应用程序,看看它什么时候花费了大部分时间。以这种方式更改关键时间不太可能产生影响。这表明,除了第一次计算它们之外,性能是相似的。