Nam G VU
Nam G VU

Reputation: 35374

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.

Upvotes: 2

Views: 5888

Answers (4)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

Regardless of performance, if you are primarily treating the object as an array of char, your code is likely to be clearer if you make it an array of char.

The only way to know whether the overhead of the repeated charAt calls matters more than the cost of copying the char[] once is to measure with your actual operations and string lengths.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

If you see Source code of charAt() comments,you find the answer.

It already returns from its char array only,So there is no way to compare it again.

  private final char value[];

Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the char value specified by the index is a surrogate, the surrogate value is returned.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

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.

Upvotes: 7

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51711

Actually, the String class already does that because it holds its contents as a char[].

String#charAt() returns

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

where value is the char[] holding the string and offset is something that lets two or more Strings share the same character array like when one is a sub-string of another.

Upvotes: 1

Related Questions