I came across code like below several times:
for (char c : s.toCharArray()) {
....
}
I'm wondering if s.toCharArray()
only excuted once or excuted s.length
times? And what about the case below?
for (int i = 0; i < s.toCharArray().length; i++) {
....
}
Inspired by comments, did some test:
Case 1: excution time : 692.664
String s = "dfsdfjglsdlghsl";
for(int i = 0 ; i < 25; i++){
s += s;
}
long start_time = System.nanoTime();
for(char c : s.toCharArray()){
int i = 0;
}
long end_time = System.nanoTime();
double excution_time = (end_time - start_time)/1e6;
System.out.println(excution_time);
Case 2: excution time : 688.217
String s = "dfsdfjglsdlghsl";
for(int i = 0 ; i < 25; i++){
s += s;
}
long start_time = System.nanoTime();
char[] carrays = s.toCharArray();
for(char c : carrays){
int i = 0;
}
long end_time = System.nanoTime();
double excution_time = (end_time - start_time)/1e6;
System.out.println(excution_time);
Almost the same. So, s.toCharArray()
should only be excuted once in the first case.