Android程序性能设计最佳实践
Map myMap1 = new HashMap(); HashMap myMap2 = new HashMap();
哪一种更好?
static int intVal = 42; static String strVal = "Hello, world!";
编译器生成一个类的构造方法,叫<clinit>,它会在类第一次使用的时候触发。方法会将42保存到intVal,从String表里获取一个引用给strVal。当这些值被引用后,他们访问时就能够去查找了。
static final int intVal = 42; static final String strVal = "Hello, world!";
类文件不再需要<clinit>方法了,因为常量转为了虚拟机进行处理。代码访问intVal的时候直接就能拿到42,访问strVal的时候开销也会相对更小。
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; } } }
public class Foo { public enum Shrubbery { GROUND, CRAWLING, HANGING } }
Shrubbery shrub = Shrubbery.GROUND;
for (int n = 0; n < list.size(); n++) { if (list.items[n].e == MyEnum.VAL_X) // do stuff 1 else if (list.items[n].e == MyEnum.VAL_Y) // do stuff 2 }
int valX = MyEnum.VAL_X.ordinal(); int valY = MyEnum.VAL_Y.ordinal(); int count = list.size(); MyItem items = list.items(); for (int n = 0; n < count; n++) { int valItem = items[n].e.ordinal(); if (valItem == valX) // do stuff 1 else if (valItem == valY) // do stuff 2 }
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); } } }
关键的事事:我们定义了一个内部类(Foo$Inner)直接访问了外部类的private方法和private实例。这是合法的,而且代码打印出了我们期望的"Value is 27"。
/*package*/ static int Foo.access$100(Foo foo) { return foo.mValue; } /*package*/ static void Foo.access$200(Foo foo, int value) { foo.doStuff(value); }
内部类代码会调用方法来访问外部的mValue或者调用外部的doStuff方法。这意味着上面的代码真正的情况是,你是通过的访问器访问而不是通过直接访问的代码。之前我们就讨论过了使用访问器要比直接访问变量更慢,所以这就是一个特定的语言习惯形成的一种"隐形"的性能影响。
Action
|
Time
|
Add a local variable
|
1
|
Add a member variable
|
4
|
Call String.length()
|
5
|
Call empty static native method
|
5
|
Call empty static method
|
12
|
Call empty virtual method
|
12.5
|
Call empty interface method
|
15
|
Call Iterator:next() on a HashMap
|
165
|
Call put() on a HashMap
|
600
|
Inflate 1 View from XML
|
22,000
|
Inflate 1 LinearLayout containing 1 TextView
|
25,000
|
Inflate 1 LinearLayout containing 6 View objects
|
100,000
|
Inflate 1 LinearLayout containing 6 TextView objects
|
135,000
|
Launch an empty activity
|
3,000,000
|
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。