2013-03-26 85 views
4

我正在處理一個問題,我遇到執行時間變得太大的問題,現在我正在尋找可能的優化。哪個更快,字符串或整數在Java中有hashkey?

問題:使用String或Integer作爲haskey之間是否存在任何(相當大的)性能差異?

問題是我有一個圖表,節點存儲在一個散列表中,以String作爲鍵。例如,鍵如下 - 「0011」或「1011」等。現在我可以將它們轉換爲整數,如果這意味着執行時間的改進。

+1

字符串的哈希碼被緩存,所以它應該沒有太大的區別。問題可能在其他地方......您應該剖析您的代碼以找到瓶頸。注意:在單線程情況下,HashMap將比Hashtable執行略好。 – assylias 2013-03-26 08:20:54

+1

我建議你分析你的應用程序,看看它花費了大部分時間。通過這種方式改變關鍵時間不太可能會產生影響。 – 2013-03-26 08:32:09

回答

3

如果您遇到性能問題,這個問題很可能不是由於HashMap/HashTable造成的。雖然散列字符串比散列整數稍微昂貴一點,但它的差別很小,並且hashCode被緩存,因此如果使用相同的字符串對象,則不會重新計算它,您不可能首先將其轉換爲整數,從而獲得任何顯着的性能優勢。

在其他地方尋找性能問題的來源可能更有成效。你有沒有嘗試分析你的代碼?

4

整數將比字符串執行更好。以下是兩者的哈希碼計算代碼。

整數的散列碼執行

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

這表明,除了第一次計算它們之外,性能是相似的。 – assylias 2013-03-26 08:25:01

0

有在速度差。 HashMaps將使用hashCode根據該代碼計算桶,Integer的實現比String更簡單。

話雖如此,如果您有執行時間的問題,您需要做一些適當的測量和分析自己。這是找出執行時間問題的唯一方法,使用Integers而不是Strings通常只會對性能產生最小影響,這意味着您的性能問題可能在其他地方。

例如,如果您想要執行一些適當的微基準,請參閱this post。還有許多其他資源可用於性能分析等。

相關問題