JAVA局部變數加final修飾的好處

來源:互聯網
上載者:User
一般來說有以下這幾種用法:
1、for迴圈中,使用局變數來儲存迴圈數次,並用final修飾,而非直接用getCount()、getSize()、lenght等
2、需要訪問集合中的某個對象時,使用局部變數來引用,並用final修飾,而非直接引用
3、需要訪問外部某個對象時,使用局部變數來引用,並用final修飾,而非直接引用
4、其它情況
 
個人理解的好處有:
1、訪問局部變數要比訪問成員變數要快
2、訪問局部變數要比每次調用方法去擷取對象要快
3、使用final修飾可以避免變數被重新賦值(引用賦值)
4、使用final修飾時,JVM不用去跟蹤該引用是否被更改。
 
以下是網上看到的一些見解:
 
Accessing a local variable is faster than accessing a field.  It's best to keep field accesses out of performance-critical inner loops when possible.  (Profile first, of course, to see if it matters.)  In theory the JVM could "inline" the field to a local variable automatically under the right conditions, but don't count on it.
 
A final local variable is not any different from a normal local variable at runtime.  The "final" keyword on a local variable expresses a constraint on the source code (that it is assigned to once) which the compiler can easily check.
 
Final *fields* do allow additional optimizations, and static final fields with primitive values (as in "public static final int MY_CONSTANT = 3") are treated as compile-time constants and inlined.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.