WEB开发网
开发学院手机开发Android 开发 Android 高效编程注意事项 阅读

Android 高效编程注意事项

 2010-03-22 21:13:00 来源:WEB开发网   
核心提示:可以写成如下:static final int intVal = 42;static final String strVal = "Hello, world!";8, Use Enhanced For Loop Syntax With Caution谨慎使用增强的for循环,Android 高效编程

可以写成如下:

static final int intVal = 42;

static final String strVal = "Hello, world!";

8, Use Enhanced For Loop Syntax With Caution

谨慎使用增强的for循环,因为它创建多余临时变量。

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()使用jdk1.5以上版本的增强for循环,这是有编译器拷贝数组的引用和长度到本地这在主循环体会产生额外的本地装载和存储,这跟one()相比,比其运行时间长一小点,同时也比one()多4byte的存储空间u

To summarize all that a bit more clearly: enhanced for loop syntax performs well with arrays, but be cautious when using it with Iterable objects since there is additional object creation.

9, Avoid Enums

避免使用枚举。

10, Use Package Scope with Inner Classes

建议使 用内部类

public class Foo {

private int mValue;

public void run() {

Inner in = new Inner();

mValue = 27;

in.stuff();

}

private void doStuff(int value) {

System.out.println("Value is " + value);

}

private class Inner {

void stuff() {

Foo.this.doStuff(Foo.this.mValue);

Tags:Android 高效 编程

编辑录入:coldstar [复制链接] [打 印]
赞助商链接