Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is faster, equalsIgnoreCase or compareToIgnoreCase

Tags:

java

string

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

equalsIgnoreCase(String anotherString)

compareToIgnoreCase(String str)

Which one is faster?

like image 352
bluegene Avatar asked May 08 '09 09:05

bluegene


2 Answers

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.

like image 125
Jon Skeet Avatar answered Nov 15 '22 21:11

Jon Skeet


if you worry about performances... measure it

like image 32
dfa Avatar answered Nov 15 '22 21:11

dfa