Java中声明常量为什么用static修饰
来源:互联网 发布:ismo软件 编辑:程序博客网 时间:2024/05/19 05:31
在做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.
看完Google的这段文章,虽然对里面部分名词还是稍有不解,但是了解到static final搭档的另外原因。
- Java中声明常量为什么用static修饰
- java为什么非静态内部类中不能有static修饰的属性,但却可以有常量?
- Java中static为什么不能修饰局部变量?
- Java中static为什么不能修饰局部变量?
- 为什么接口中的常量必须使用public static final修饰
- 为什么接口中的常量必须使用public static final修饰
- c++中 static修饰修饰类声明部分
- Java中static的用法,static、public为什么不能修饰局部变量?
- Java中static修饰符
- java中static修饰符
- java中static修饰符
- Java中static声明变量
- 为什么java接口中可以有default或者static修饰的方法?
- Java中关于static修饰符
- java中static修饰class说明
- java 中static修饰变量的初始值
- Java中static修饰类的问题
- java中static修饰特殊的类
- ArrayAdapter<T>,Filter实现列表搜索
- Python GUI编程各种实现的对比
- xp下使用thrift
- 关于CLR、CIL、CTS、CLS、CLI、BCL和FCL。
- iOS学习----------正则表达式
- Java中声明常量为什么用static修饰
- 27个提升效率的iOS开源库推荐
- 黑马程序员----java基础面向对象特点及封装
- 引子
- 第 3 章 自定义数据库表结构
- 【PHP】PHP中__get()和__set()的用法实例详解
- OGG_Manager 进程
- 编译器括号检查原理(C)
- CSDN下载手机客户端,存在 BUG,两个苹果下载图标