• Post Reply Bookmark Topic Watch Topic
  • New Topic

String's hashcode caching  RSS feed

 
Ranch Hand
Posts: 413
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I read a post from Winston Gutkowski in one of the threads that one of the advatanges of String being immutable is that its hashcode could be cached. How does this work? I read somewhere that each String's hashcode is stored in a private int variable, but I don't understand how it is reused.

Thanks,
Prasanna
 
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


There's the code which reuses that private int variable. Somewhere else there must be code which calculates the hash code and assigns it to that variable, but I haven't included that. It could be done upon initialization of the object, or it could be done upon the first call of the hashCode() method. You could have a look at the code yourself if you're interested; it's in the src.zip file which was installed along with your Java installation.

Also if Winston used the word "could", that implies that String doesn't necessarily do that optimization. And I don't know whether it really does or not, either. Again, you could look at its source code if you wanted to find out.

Note also that any class could use the same technique, because an object's hash code is not supposed to ever change. But you won't see it used very often because it's a micro-optimization which is unlikely to provide any major improvement in speed.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!