Compare Strings of same length faster using the hashcode:
public static boolean equals(final String s1, final String s2) {
return s1 != null && s2 != null && s1.hashCode() == s2.hashCode()
&& s1.equals(s2);
}
You can test it, my results are for 4000000 compare operations including identical, equal and different strings:
String.equals(String): 177081939
equals(String, String): 44153608
Note: Calculating the hashCode of a new string object takes some computation time and afterwards the hashCode is stored in the object. So my suggested improvement will only be faster than the default compare if string objects are reused. In my application I am using String constants and store strings in collections. Multiple comparisons of strings using my method are actually faster for me, but it may not be in general.
If the method is used with new strings all the time like compare("a", "b")
, it won't be an improvement.
So the fastest way of comparing strings depends on:
- Whether your string objects are reused (like from a collection) or are always new (like from an input stream)
- Whether your strings have different lengths
- Whether your strings differ at the start or the end of the string
- Your programming style, how much constants are used
- Your use of String.intern()
Ignoring those facts, the majority of all programs will be fine with String.equals().