我应该避免在 Android 4.0+ 中为 ArrayList 使用 foreach 吗?
Should I avoid foreach for ArrayList in Andorid 4.0+?
我刚从 Hellman, Erik 的书 "Android Programming - Pushing the Limits" 中读到这篇文章。第 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.
我之前搜索过,foreach和普通的for循环在Java中没有性能差异,只有Android(版本4+)有什么特殊原因吗?
请检查有关循环的信息here
我刚从 Hellman, Erik 的书 "Android Programming - Pushing the Limits" 中读到这篇文章。第 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.
我之前搜索过,foreach和普通的for循环在Java中没有性能差异,只有Android(版本4+)有什么特殊原因吗?
请检查有关循环的信息here