JAVA局部变量加final修饰的好处

xiaoxiao2021-02-28  155

一般来说有以下这几种用法: 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.
转载请注明原文地址: https://www.6miu.com/read-48965.html

最新回复(0)