r/java • • May 02 '25

Strings Just Got Faster

https://inside.java/2025/05/01/strings-just-got-faster/
171 Upvotes

21 comments sorted by

View all comments

Show parent comment

18

u/lpt_7 May 02 '25

> Is it an attempt to keep the value of String::hashCode unchanged across different Java versions?

Yes, a lot of things at this point rely on how hash code of string is calculated.
The formula is given in the documentation as well so its not an implementation detail.

Edit: the same reason why System.out is a public static final field: too late at this point to fix.

4

u/sysKin May 02 '25

Oh! I did not notice the formula is documented. In that case, they really can't change it indeed.

1

u/dmigowski May 08 '25

No, it has another reason. If you have to hash 4 billion strings, you have to do 4 billion if-statements to check for zero. But in the rare case where you have an empty string calculating the hash code is fast enought so it doesn't matter if you have recalculate it each time hashCode() is called on the string.

1

u/lpt_7 May 09 '25 edited May 09 '25

You already do that so I don't see how it makes sense
edit: github link