JAVA局部变量加final修饰的好处
来源:互联网 发布:办公软件有哪些 编辑:程序博客网 时间:2024/05/22 01:22
一般来说有以下这几种用法:
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.
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.
阅读全文
0 0
- JAVA局部变量加final修饰的好处
- java中final修饰的局部变量
- 关于Java Final 修饰的局部变量,多线程可以访问
- java面试题:final修饰局部变量的问题
- 为什么内部类访问局部变量需要加final修饰?
- Java里final修饰的类变量,实例变量和局部变量
- Java final修饰的变量
- java中内部类访问局部变量的时候,为什么变量必须加上final修饰
- 于java里方法的内部类只能访问被final修饰的局部变量和.
- java匿名类使用的局部变量只能用final修饰?
- 深入理解final在Java和Android中修饰局部变量的意义
- JAVA中内部类(匿名内部类)访问的局部变量为什么要用final修饰?
- JAVA中内部类(匿名内部类)访问的局部变量为什么要用final修饰?
- [java]final修饰变量
- Java中用final修饰的变量
- java中final可以修饰的变量
- Java匿名类中使用的局部变量为何要加final
- final修饰的变量
- SimpleDateFormat日期格式转换
- 单位和值
- adb push
- 集群项目session 共享方案
- 自定义Java线程池
- JAVA局部变量加final修饰的好处
- spring-boot起步介绍Demo,廖师兄springboot学习笔记
- oracle添加栏位
- 原型模式
- Android四大组件-内容提供者
- Zurmo开发的小技巧(8)
- QML之Grid网格定位器
- eclipse maven项目中修改 tomcat 部署路径
- Spring MVC中的@ModelAttribute