Java字符串 - 比较charAt()和索引运算符[]

Nam*_* VU 1 java string indexing character

我想知道使用.charAt()是否比将字符串变量转换s为char [] a数组更快,a[i]而不是通过s.charAt(i)

假设我们正在研究字符串中每个字符上有很多运算符的问题.

Sot*_*lis 7

实施String#charAt(int index)了Oracle的Java 7:

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

检查有点安全,但这是完全相同的行为.

返回它实际上会更慢 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;
}
Run Code Online (Sandbox Code Playgroud)

因为你必须先复制它.