Java中聲明常量為什麼用static修飾

來源:互聯網
上載者:User

標籤:靜態常量   常量   java   

在做Android開發的時候,只要查看一些Android源碼,不難發現,其中,聲明常量都是如下格式:

<span style="font-size:14px;">private static final String TAG = "FragmentActivity";</span>

聲明為什麼要添加static關鍵字呢?

之前是這麼考慮問題的:定義一個類A,其中包含了用靜態變數修飾的常量CONSTANT_A與直接用final修飾的常量CONSTANT_B

<span style="font-size:14px;">public class A {    public static final String CONSTANT_A = "Hello";    public final String CONSTANT_B = "Hello";}</span>

在建立多個A的對象時,常量A在記憶體中只有一份拷貝,而B則有多個拷貝,後者顯然使我們不希望看到的。


今天在看Android官網的時候,恰巧看到這一問題:

http://developer.android.com/training/articles/perf-tips.html

原文:

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 <clinit>, 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 for strVal. When these values are referenced later on, they are accessed with field lookups.

在類第一次被執行的時候,編譯器會產生一個初始化方法,這個方法將42的值存入對應的變數intVal,同時通過常量表獲得strVal的一個引用。在之後引用這些變數的時候,將進行查詢(表)來訪問到。

We can improve matters with the "final" keyword:

通過使用final來提升效能:

static final int intVal = 42;static final String strVal = "Hello, world!";

The class no longer requires a <clinit> 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.

這樣,常量進入了dex檔案的靜態區初始化部分,不在需要一個初始化方法(來對變數賦值),代碼中將直接使用42的常量值,strVal也通過開銷低廉的“字串常量”來代替檔案查表。

Note: This optimization applies only to primitive types and String constants, not arbitrary reference types. Still, it‘s good practice to declare constants static final whenever possible.

最有的一個小提示:這種右劃僅對基礎資料型別 (Elementary Data Type)和String常量有效果,不包括其他參考型別。


看完Google的這段文章,雖然對裡面部分名詞還是稍有不解,但是瞭解到static final搭檔的另外原因。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java中聲明常量為什麼用static修飾

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.