I just read this from the book "Android Programming - Pushing the Limits" by Hellman, Erik. Page 38:
void loopOne(String[] names) {
int size = names.length;
for (int i = 0; i < size; i++) {
printName(names[i]);
}
}
void loopTwo(String[] names) {
for (String name : names) {
printName(name);
}
}
void loopThree(Collection<String> names) {
for (String name : names) {
printName(name);
}
}
void loopFour(Collection<String> names) {
Iterator<String> iterator = names.iterator();
while (iterator.hasNext()) {
printName(iterator.next());
}
}
// Avoid using enhanced for-loops for ArrayList
void loopFive(ArrayList<String> names) {
int size = names.size();
for (int i = 0; i < size; i++) {
printName(names.get(i));
}
}
These methods show four different ways of looping through collections and arrays. The first two methods have the same performance, so it’s safe to use the enhanced for-loop on arrays if you’re just going to read the entries. For Collection objects, you get the same performance when using the enhanced for-loop as when you manually retrieve an Iterator for traversal. The only time you should do a manual for-loop is when you have an ArrayList object.
I searched before, the foreach and the normal for loop have no performance difference in Java, is there any special reason only for Android (version 4 +)?
0 comments:
Post a Comment