atom feed1 message in tip - use String.charAt
FromSent OnAttachments
Bill ShannonJul 21, 2008 12:24 pm 
Subject:performance tip - use String.charAt
From:Bill Shannon (
Date:Jul 21, 2008 12:24:54 pm

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.