gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:56:22 24 4
gpt4 key购买 nike

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

问题:使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com