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