String Comparisons and Searches
String comparison
performance is highly dependent on both the string data and the
comparison algorithm (this is really a truism about collections in
general). The methods that come with the String
class have a performance advantage in being able to directly access
the underlying char collection. So if you need to
make String comparisons, String
methods usually provide better performance than your own methods,
provided that you can make your desired comparison fit in with one of
the String methods. Another necessary
consideration is whether comparisons are case-sensitive or
-insensitive, and I will consider this in more detail shortly.
To optimize for string
comparisons, you need to look at the source of the comparison methods
so you know exactly how they work. As an example, consider the
String.equals( ) and
String.equalsIgnoreCase( ) methods from the Java 2
distribution.
String.equals(Object)
runs in a fairly straightforward way:
it first checks for object identity, then for
null, then for String type,
then for same-size strings, and then character by character, running
from the first characters to the last. Efficient and complete.
String.equalsIgnoreCase(String)
is a little more complex. It checks
for null, and then for strings being the same size
(the String type check is not needed, since this
method accepts only String objects). Then, using a
case-insensitive comparison,
regionMatches( ) is
applied. regionMatches( ) runs a character-by-character ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access