12

If I want to check every char in a String using String.charAt(int i), would it count from start every time or it is converted to an array automatically and get the charAt index directly?

Would it be more efficient if I create a char array by String.toCharArray() and then go through the array by index?

Can I check this up in JavaDoc? Where?

tshepang
  • 12,111
  • 21
  • 91
  • 136
Zoe
  • 997
  • 4
  • 10
  • 19

1 Answers1

20

The JRE is mostly open source. You can download a zip file here or browse online with websites like grepcode.

String.charAt:

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
  • 1
    Note, however, that specific JREs might not use the open-source implementation for all library classes. A publisher might replace part of it, eg for performance reasons, as long as they can prove that their version completely conforms to the spec and passes all the tests. Also note that the JIT compiler may substantially rewrite your code, and JITCs definitely vary from publisher to publisher and platform to platform. So when you're asking questions about performance rather than about behavior, there's always a huge "it depends" attached to any possible answer. – keshlam Jan 03 '14 at 00:40
  • 2
    In general, you can and should assume that the folks writing compilers and libraries have already put a lot of effort into optimizing their code, and may have used hand-coded bytecodes or native code to optimize things in ways normal Java code can't. Unless you have evidence otherwise or a special case you can take advantage of, you can usually assume the library performance is pretty darned good and put your effort into optimizing which of these canned operations you use, how, in what higher-level algorithms. – keshlam Jan 03 '14 at 00:45