dev@glassfish.java.net

performance tip - use String.charAt

From: Bill Shannon <bill.shannon_at_sun.com>
Date: Mon, 21 Jul 2008 12:25:17 -0700

While reviewing some code recently I had a question...

If I have some cases where I need to loop over every character in a String
and check it, when is it better to use String.getChars() and loop over
the char array, and when is it better to use String.charAt()? If the
String is large, creating a new char array creates a lot of garbage.
If the String is (likely) small, is using the char array faster enough
to be worth it? Is HotSpot good enough at eliminating the method call
cost that charAt doesn't matter?

After consulting with our performance expert (Scott), the answer is simple -
use charAt. Scott says:

> Hotspot will easily inline this method, so if you execute it enough
> times, that difference goes away, and the resulting offset addition will
> be in the end faster than the GC overhead caused by copying the arrays.
> If you don't execute enough times, then the performace differences in
> either case aren't likely to impact your program.