Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't String's hashCode() cache 0?
    text
    copied!<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="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>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload