tags:

views:

815

answers:

3

In a java app, assuming I have option of choosing the following comparison methods

equalsIgnoreCase(String anotherString)

compareToIgnoreCase(String str)

Which one is faster?

Thanks in Advance

+7  A: 

if you worry about performances... measure it

dfa
Too easy! There has to be a way that wastes more people’s time!
Bombe
indeed, very nice answer it isn't?
dfa
It's actually very easy to come to wrong conclusions using measuring in this case, since the outcome very much depends on exactly what you measure. It's good to garner some insight first - see Jon Skeet's answer for a good example.
Software Monkey
+5  A: 

equalsIgnoreCase can be a lot faster. For example, consider two strings which start with the same 10,000 characters - but one of them has an extra character at the end. equalsIgnoreCase can return immediately; compareToIgnoreCase has to iterate to the end of the string to see the difference.

But generally I'd go with whichever expresses your intention better. This works well for performance too: assuming I'm right in saying that equalsIgnoreCase is at least as fast as compareToIgnoreCase, it means you should use that where you can - if you need an actual ordering, you've got to use compareToIgnoreCase anyway.

Jon Skeet
@Downvoter: Care to give a reason?
Jon Skeet
+3  A: 

Looking at the 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 it looks at the actual string character by character (which also happens in a similar fashion for compareToIgnoreCase), equalsIgnoreCase also checks for reference identity and character length, which could be very much faster.

Thilo
Or it could be a waste of time when most strings are different :)
Aaron Digulla
sure, it's a trade-off. But these two comparisons are very fast, so you lose not much. And the length comparison should be quite effective (detect a lot of different string very quickly).
Thilo