It appears in java.lang.String.java, that Java will only generate the hashcode, and then store it, after a call to hashcode(), but why not just make the hashcode in the constructor?
The relevant code:
if (h == 0 && count > 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
could for the most part be placed in the constructor.
Why spend time generating a hash code that most likely will not be used? Most strings are constructed, used and then garbage collected without the hashcode() ever being called.
Joshua Bloch call this practice 'racy single-check'.
Jeremy Manson has excellent explanation of why it's done and why it'safe: on his blog
In essence, at construction time you save some time by skipping calculating hash code. In multithreaded environment you'll pay for this back because multiple thread potentially could do the same calculation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With