I need to compare 2 Strings
. I have following methods I could think of:
equalsIgnoreCase
- Heard that this is the fastest, but i can't use it as my String is case sensitivematches
- Probably the slowest oneequals
compareTo
So in the above option, I am left with equals
and compareTo
. Which one is faster among these?
Note: Input number of Strings are huge in number [around 5000 per sec].
Note a very important difference between compareTo
and equals
:
"myString".compareTo(null); //Throws java.lang.NullPointerException
"myString".equals(null); //Returns false
Now I advise you to review the source code of both methods to conclude that equals
is preferable over compareTo
that involves some Math
calculations.
Also note that equals
makes a ==
first! This might be a big advantage when the objects are identical. Specially when you mentioned that you have a huge amount of Strings, because Java interns Strings, this might happen more than you thought.
Although you asked about Strings, but I want to add this note:
These methods can be very different when BigDecimal
is involved. For example, see the docs:
equals compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
I am left with equals and compareTo.
Both serves in different purposes.
CompareTo
the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.
Where as
equals
true if the given object represents a String equivalent to this string, false otherwise
Hence compareTo()
need more calculations that equals()
You can see the proof of that in source code of both.
compareTo()
equals() ----- prefer to use this.
equalsIgnoreCase
You generally use this one for string comparison.
matches
Slow because it is RegEx-based.
equals
I don't think this is slower than equalsIgnoreCase
compareTo
This returns an integer, or 0. This is used in sorting, for example. Don't use it for equality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With