Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparision with equals and compareTo - which is faster?

Tags:

java

string

I need to compare 2 Strings. I have following methods I could think of:

  1. equalsIgnoreCase - Heard that this is the fastest, but i can't use it as my String is case sensitive
  2. matches - Probably the slowest one
  3. equals
  4. 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].

like image 840
G.S Avatar asked Oct 21 '13 06:10

G.S


3 Answers

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).

like image 159
Maroun Avatar answered Nov 14 '22 23:11

Maroun


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.

like image 39
Suresh Atta Avatar answered Nov 14 '22 22:11

Suresh Atta


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.

like image 27
Georgian Avatar answered Nov 14 '22 21:11

Georgian