In Java (maybe the same for other langues as well) the charAt(x)
method for accessing characters in a string is much slower than accessing the character elements in a char[]
. This doesn't make much sense to me since String is using a char[]
to represent the data.
Here is my test and results on this.
Testing charAt()
for(int i = 1000000; i >= 0; i--){
char c = s.charAt(5);
}
charAt()
elapsed time = 0.00261095
for(int i = 1000000; i >= 0; i--){
char c = sArr[5];
}
arr[]
elapsed time 0.001620297
From String.Java
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}