android 官方推荐除了ArrayList
,别的collections 使用增强LOOP ,也就是foreach ArrayList 使用手写计数loop without size
以下为官方原文
static class Foo {
int mSplat;
}
Foo[] mArray = ...
public void zero() {
int sum = 0;
for (int i = 0; i < mArray.length; ++i) {
sum += mArray[i].mSplat;
}
}
public void one() {
int sum = 0;
Foo[] localArray = mArray;
int len = localArray.length;
for (int i = 0; i < len; ++i) {
sum += localArray[i].mSplat;
}
}
public void two() {
int sum = 0;
for (Foo a : mArray) {
sum += a.mSplat;
}
}
复制代码
zero()
is slowest, because the JIT can’t yet optimize away the cost of getting the array length once for every iteration through the loop.
one()
is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance benefit.
two()
is fastest for devices without a JIT, and indistinguishable from one() for devices with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language.
So, you should use the enhanced for
loop by default, but consider a hand-written counted loop for performance-critical [ArrayList](https://developer.android.google.cn/reference/java/util/ArrayList.html)
iteration.
转载于:https://juejin.im/post/5c8755b35188257ddb6afd36
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/101056.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...