Last year I made some simple performance measurements to see whether it was faster when scanning the characters in a string to use s.charAt(k) == 'x' or to first convert to an array of char and use c[k] == 'x'. Obviously this is in no way a general performance test, I just did it because I wanted to try and optimize some heavily run code.
Anyway, the results first. I used open office to plot the graph. The y axis shows the time in milliseconds to scan a string 50,000 times. It's the average of 50 runs. The x axis shows the length in characters of the string being scanned. The legend at the bottom shows the method used (toChar or charAt), the java version (131 or 140) and whether the -server or -hotspot (S or H) flag was supplied.
Using the -server flag made the biggest difference in the tests. For strings over 25 characters in length it provides the greatest speed. Apart from a strange bump for string lengths between 10 and 25 characters, which persists when I rerun the tests, the fastest technique is -server, using charAt, and running 131. On the other hand the slowest was -hotspot, using charAt, and running 131. Changing version to 140 improved things quite a bit.
With version 131, when using -hotspot, it used to be worth using charAt for short strings, under about 8 characters in length, and switching to toChar for longer strings. With version 140 that point has now moved out to around 75 characters. If you're using the -server flag, which most java code does, it's always faster to use charAt.
If you're interested in running the tests yourself the java code's here.
Posted by Alex at September 07, 2002 09:49 PM