title: Why doesn't String's hashCode() cache 0?
body: <p>I noticed in the Java 6 source code for String that hashCode only caches values other than 0. The difference in performance is exhibited by the following snippet:</p>
  
  <pre><code>public class Main{
     static void test(String s) {
        long start = System.currentTimeMillis();
        for (int i = 0; i &lt; 10000000; i++) {
           s.hashCode();
        }
        System.out.format("Took %d ms.%n", System.currentTimeMillis() - start);
     }
     public static void main(String[] args) {
        String z = "Allocator redistricts; strict allocator redistricts strictly.";
        test(z);
        test(z.toUpperCase());
     }
  }
  </code></pre>
  
  <p><a href="https://web.archive.org/web/20000000000000/http://www.ideone.com/Ho9lfOKy" rel="noreferrer">Running this in ideone.com</a> gives the following output:</p>
  
  <pre><code>Took 1470 ms.
  Took 58 ms.
  </code></pre>
  
  <p>So my questions are:</p>
  
  <ul>
  <li>Why doesn't String's hashCode() cache 0?</li>
  <li>What is the probability that a Java string hashes to 0?</li>
  <li>What's the best way to avoid the performance penalty of recomputing the hash value every time for strings that hash to 0?</li>
  <li>Is this the best-practice way of caching values? (i.e. cache all except one?)</li>
  </ul>
  
  <hr>
  
  <p>For your amusement, each line here is a string that hash to 0:</p>
  
  <pre><code>pollinating sandboxes
  amusement &amp; hemophilias
  schoolworks = perversive
  electrolysissweeteners.net
  constitutionalunstableness.net
  grinnerslaphappier.org
  BLEACHINGFEMININELY.NET
  WWW.BUMRACEGOERS.ORG
  WWW.RACCOONPRUDENTIALS.NET
  Microcomputers: the unredeemed lollipop...
  Incentively, my dear, I don't tessellate a derangement.
  A person who never yodelled an apology, never preened vocalizing transsexuals.
  </code></pre>