Looks like niether is faster or slower
public static void main(String arguments[]) {
//Build a long string
StringBuilder sb = new StringBuilder();
for(int j = 0; j < 10000; j++) {
sb.append("a really, really long string");
}
String str = sb.toString();
for (int testscount = 0; testscount < 10; testscount ++) {
//Test 1
long start = System.currentTimeMillis();
for(int c = 0; c < 10000000; c++) {
for (int i = 0, n = str.length(); i < n; i++) {
char chr = str.charAt(i);
doSomethingWithChar(chr);//To trick JIT optimistaion
}
}
System.out.println("1: " + (System.currentTimeMillis() - start));
//Test 2
start = System.currentTimeMillis();
char[] chars = str.toCharArray();
for(int c = 0; c < 10000000; c++) {
for (int i = 0, n = chars.length; i < n; i++) {
char chr = chars[i];
doSomethingWithChar(chr);//To trick JIT optimistaion
}
}
System.out.println("2: " + (System.currentTimeMillis() - start));
System.out.println();
}
}
public static void doSomethingWithChar(char chr) {
int newInt = chr << 2;
}
For long strings I'll chose the first one. Why copy around long strings? Documentations says:
public char[] toCharArray() Converts this string to a new character array.
Returns: a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
//Edit 1
I've changed the test to trick JIT optimisation.
//Edit 2
Repeat test 10 times to let JVM warm up.
//Edit 3
Conclusions:
First of all str.toCharArray();
copies entire string in memory. It can be memory consuming for long strings. Method String.charAt( )
looks up char in char array inside String class checking index before.
It looks like for short enough Strings first method (i.e. chatAt
method) is a bit slower due to this index check. But if the String is long enough, copying whole char array gets slower, and the first method is faster. The longer the string is, the slower toCharArray
performs. Try to change limit in for(int j = 0; j < 10000; j++)
loop to see it.
If we let JVM warm up code runs faster, but proportions are the same.
After all it's just micro-optimisation.