Which is faster equalsIgnoreCase or compareToIgnoreCase

In a java application, assuming I have the option to select the following comparison methods

equalsIgnoreCase (String anotherString)

compareToIgnoreCase (String str)

Which one is faster?

+6
java string
source share
3 answers

equalsIgnoreCase can be much faster. For example, consider two lines starting with the same 10,000 characters, but one of them has an extra character at the end. equalsIgnoreCase may return immediately; compareToIgnoreCase must iterate to the end of the line to see the difference.

But in general, I would go with what expresses your intention better. This works well for performance: assuming I'm right in saying that equalsIgnoreCase is at least as fast as compareToIgnoreCase , it means you should use this where you can - if you need the actual order, you should use compareToIgnoreCase anyway.

+28
source share

if you are worried about performances ... measure

+10
source share

Looking for source for java.lang.String

  public boolean equalsIgnoreCase(String anotherString) { return (this == anotherString) ? true : (anotherString != null) && (anotherString.count == count) && regionMatches(true, 0, anotherString, 0, count); } 

So, before he looks at the actual character of a string by character (which also happens similarly for compareToIgnoreCase ), equalsIgnoreCase also checks the link identifier and character length, which can be much faster.

+4
source share

All Articles