如何编写高效的Android代码
2010-06-01 04:33:00 来源:WEB开发网谨慎使用foreach
foreach可以用在实现了Iterable接口的集合类型上。foreach会给这些对象分配一个iterator,然后调用 hasNext()和next()方法。你最好使用foreach处理ArrayList对象,但是对其他集合对象,foreach相当于使用 iterator。
下面展示了foreach一种可接受的用法:
Java代码
public class Foo {
int mSplat;
static Foo mArray[] = new Foo[27];
public static void zero() {
int sum = 0;
for (int i = 0; i < mArray.length; i++) {
sum += mArray[i].mSplat;
}
}
public static void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; i++) {
sum += localArray[i].mSplat;
}
}
public static void two() {
int sum = 0;
for (Foo a: mArray) {
sum += a.mSplat;
}
}
}
public class Foo {
int mSplat;
static Foo mArray[] = new Foo[27];
public static void zero() {
int sum = 0;
for (int i = 0; i < mArray.length; i++) {
sum += mArray[i].mSplat;
}
}
public static void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; i++) {
sum += localArray[i].mSplat;
}
}
public static void two() {
int sum = 0;
for (Foo a: mArray) {
sum += a.mSplat;
}
}
}
在zero()中,每次循环都会访问两次静态成员变量,取得一次数组的长度。
retrieves the static field twice and gets the array length once for every iteration through the loop.
更多精彩
赞助商链接