combining hashCode() and equals() is faster?

So I am doing some research on fastest on comparing strings and found this code:

if (s1.hashCode() == s2.hashCode() && s1.equals(s2))

My question is: Why is it faster? Cause what I think is that it take more computer cycle than just saying with no &&.

Jon Skeet
people
quotationmark

Java strings cache their hash codes - so if the hash codes are equal, the strings are very likely to be equal. A full equality check could take much longer, if the strings are the same length and only differ near the very end. (The implementation of equals in String first checks the lengths, before it looks at the actual code units.)

On the other hand, that requires the hash code to be computed - if it hasn't already been computed, that will be O(n) in the length of the string, whereas two strings of unequal length can be compared for equality very quickly.

So if you know that the strings have already been hashed and you're expecting there to be lots of strings with the same length1, this is an optimization - otherwise it could make things slower. I wouldn't use it in general purpose-code though - and I would add a comment explaining the reason for it, too.


1 And you don't already know that the hash codes are equal through some other mechanism, as per supercat's comment below - I'd say this is a corner case on a corner case though.

people

See more on this question at Stackoverflow