While I love parameterized types and the enhanced for loop, the one feature of Java 5 that I most adore is the old regionMatches()
[1, 2] family of functions on java.lang.String
. Here are a couple of sample use-cases that previously required the creation of new String
s or tedious loops using charAt()
:
startsWith()
If you’ve ever written code like
if (foo.toLowerCase().startsWith(bar.toLowerCase())) ...
and winced, because you were creating and throwing away two String
s, then rejoice! Now you may
if (foo.regionMatches(true, 0, bar, 0, bar.length())) ...
Before:
if (foo.equals(bar.substring(m))) ...
After:
if (foo.regionMatches(0, bar, m, bar.length() - m)) ...
Look through your own code for opportunities to use these efficient new functions.
In response to the skeptical inquiries below, here’s some benchmark code. In my opinion, the results support my idea that regionMatches()
is a win for efficiency in the context of time-critical applications. For what it’s worth, my own recent use of regionMatches()
is in a service where one fifth of a millisecond is the average response time, and where frequent garbage collection would be disruptive.