January 15, 2005

My Java Killer Feature

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 Strings or tedious loops using charAt():

Case-folding startsWith()

If you’ve ever written code like

    if (foo.toLowerCase().startsWith(bar.toLowerCase())) ...

and winced, because you were creating and throwing away two Strings, then rejoice! Now you may

    if (foo.regionMatches(true, 0, bar, 0, bar.length())) ...

Comparison of arbitrary string regions


    if (foo.equals(bar.substring(m))) ...


    if (foo.regionMatches(0, bar, m, bar.length() - m)) ...

Look through your own code for opportunities to use these efficient new functions.

Update - Jan 16, 2005

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.

Posted by MrFeinberg at 12:02 PM | Comments (6)