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.

本人擅长Ai、Fw、Fl、Br、Ae、Pr、Id、Ps等软件的安装与卸载,精通CSS、JavaScript、PHP、ASP、C、C++、C#、Java、Ruby、Perl、Lisp、Python、Objective-C、ActionScript、Pascal等单词的拼写,熟悉Windows、Linux、OS X、Android、iOS、WP8等系统的开关机。

通过下面的方式来联系我们:

电邮:138762189@qq.com

联系QQ:点击这里给我发消息

官方站:www.tadke.com

※ ※ 联系请加我的企鹅号 ※※

※ ※技术支持请微信联系站长 ※※

Copyright © 2023 Tadke.com. 琼ICP备20000547号