This is slow:
for(int i = 0, n = s.length() ; i < n ; i++) {
char c = s.charAt(i);
}
but can be faster like this:
int length = s.length();
for(int i = 0, n = length ; i < n ; ++i) {
char c = s.charAt(i);
}
where the differences:
- extracted the length to a variable to prevent recalculate this again and again.
- ++i is faster the i++ because does not need a temporal variable and garbage collection for it.
This is faster:
for(char c : s.toCharArray()) {
// process c
}
because it uses an iterator, and can be optimized well by Java compiler.
Iterators are always faster than simple loop (except some strange cases, where iterators do complex logic or resource hungry work)
But best to use that character iterator class in the other post here.
regards