Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 初級開發 >> Android代碼性能優化技巧

Android代碼性能優化技巧

編輯:初級開發

目前來說Android 2.2的JIT性能有了本質的提高,不過對於老版本的程序提高Java執行效率還有很多語言特點來說,今天android123提到的不是語法糖,而是基礎的問題,對於Java 1.5之後將會有明顯的改進。下面的例子來自SDK:

  static class Foo {
        int mSplat;
    }
    Foo[] mArray = ... 

  上面的靜態類Foo的執行效果和性能,我們分三個方法zero、one和two來做對比。
 
    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() { //推薦的方法,通過Java 1.5的新語法特性可以大幅改進性能
        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.

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved