Which is a faster approach when iterating over strings in Java and why?
I was going through this question and one of the answers gave 2 options and said the first one is probably faster.
I would like to know why?
The 2 options mentioned in the answer are
for(int i = 0, n = s.length() ; i < n ; i++) {
开发者_StackOverflow社区 char c = s.charAt(i);
}
or
for(char c : s.toCharArray()) {
// process c
}
The second answer suggested creates a char
array and iterates over that. This mechanism is probably slower because of the additional overhead in creating the array prior to iterating over it; this overhead correlates with the length of the String.
A third method not mentioned in the answer you've referenced involves using a StringCharacterIterator
; e.g.
CharacterIterator it = new StringCharacterIterator("Hello, World");
char c;
while ((c = it.next()) != CharacterIterator.DONE) {
System.err.println("Char: " + c);
}
However, my personal preference would be to use the first index-based solution in the answer you reference.
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
精彩评论