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

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.