2013年8月7日 星期三

[Android]開發技巧 靜態常數宣告


Use Static Final For Constants


Consider the following declaration at the top of a class:
static int intVal = 42;
static String strVal = "Hello, world!";
The compiler generates a class initializer method, called , that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the classfile string constant table forstrVal. When these values are referenced later on, they are accessed with field lookups.
We can improve matters with the "final" keyword:
static final int intVal = 42;
static final String strVal = "Hello, world!";
The class no longer requires a  method, because the constants go into static field initializers in the dex file. Code that refers to intVal will use the integer value 42 directly, and accesses to strVal will use a relatively inexpensive "string constant" instruction instead of a field lookup.

靜態常數宣告 盡可能使用 Final以減少 field lookup的動作, 而是直接參照 "字串常數".

沒有留言:

張貼留言

內容回應