2

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.

Nam G VU
  • 33,193
  • 69
  • 233
  • 372
  • 2
    [This](http://stackoverflow.com/a/11876086/645270) test isn't exactly what you're asking about, but close enough. – keyser Aug 08 '13 at 14:35
  • Not just close & it answers this question: it depends on string length (or actually how many times you access a char AND the string length which is the same if you loop over every character) – zapl Aug 08 '13 at 17:13

4 Answers4

7

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Yeah! I didn't think that I can view to source code of the method ^^ The habit from coding with C# I guess. Thank you! – Nam G VU Aug 08 '13 at 15:48
1

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.

Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
1

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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

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.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75