返回
顶部

修改密码

Android编程中for循环性能

+1

-1

收藏

+1

-1

点赞0

评论0

先看下面这段代码 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 sta…
先看下面这段代码
 
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() 获取静态属性两次,每次循环都获取数组长度一次。
 
one() 将所有静态属性引用到本地变量,避免静态成员的查询。
 
two() uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language. The code generated by the compiler takes care of copying the array reference and the array length to local variables, making it a good choice for walking through all elements of an array. It does generate an extra local load/store in the main loop (apparently preserving "a"), making it a teensy bit slower and 4 bytes longer than one().
 
总结:
 
使用增强for循环来处理数组性能是最好的,但必须注意避免附加的对象创建。

扫一扫在手机打开

评论
已有0条评论
0/150
提交
热门评论
相关推荐
如何编写高效的Android代码
  • 程序优化
  • 2022-05-20 18:33
  • 0 0 0
+1
Android编程中for循环性能
  • 程序优化
  • 2022-05-20 18:33
  • 0 0 0
+1
Android内存泄漏的原因讲解
  • 程序优化
  • 2022-05-20 18:33
  • 0 0 0
+1
android 优化耗电量性能
  • 程序优化
  • 2022-05-20 18:33
  • 0 0 0
+1
Android App 性能优化 安卓开发教程
  • 程序优化
  • 2022-05-20 18:33
  • 0 0 0
+1
今日要闻
换一批
热点排行