What\'s the quickest to compare two strings in Java?
Is there something faster than equals?
EDIT: I can not help much to clarify the problem.
I have
I had tries different combinations for string comparison (code here):
1. s1.equals(s2)
2. s1.length() == s2.length() && s1.hashCode() == s2.hashCode() && s1.equals(s2)
3. s1.hashCode() == s2.hashCode() && s1.equals(s2);
4. s1.length() == s2.length() && s1.equals(s2);
I used strings of 40 chars length, in 10000000000L iterations and before any iteration I reinitialized the strings.
for equal stings I got:
equal: 2873 milis ???
equal: 21386 milis
equal: 7181 milis
equal: 2710 milis ???
for same size strings but last char different I got:
different: 3011 milis
different: 23415 milis
different: 6924 milis
different: 2791 milis
for different sizes, almost same strings but one char added at the end for s2:
different size: 3167 milis
different size: 5188 milis
different size: 6902 milis
different size: 2951 milis
seems to me it is best to use first a string.length() comparison before equals().
But this will not matter almost at all because this is the case where I have 10^10 string comparisons with 40 chars length and what is bizarre for me is the case where for equal strings I have a better speed when I compare the string length first.