Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string - compare charAt() and index operator []

I wonder whether it is slower to use .charAt() than convert the string variable s to char[] a array and access it via a[i] instead of s.charAt(i) ?

Let's say we are working on problem that has lots of operator on each character within the string.

like image 693
Nam G VU Avatar asked Dec 04 '25 03:12

Nam G VU


1 Answers

The implementation of String#charAt(int index) for Oracle's Java 7:

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

It's a little safer with the check, but it's the exact same behavior.

It would actually be slower to return the char[]

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

since you have to copy it first.

like image 132
Sotirios Delimanolis Avatar answered Dec 06 '25 17:12

Sotirios Delimanolis