编译时常量和变量 [英] Compile-time constants and variables

查看:42
本文介绍了编译时常量和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 语言文档说:

The Java language documentation says:

如果将原始类型或字符串定义为常量并且值在编译时已知,编译器替换常量名代码中随处可见的值.这称为编译时常数.

If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant.

我的理解是如果我们有一段代码:

My understanding is if we have a piece of code:

private final int x = 10;

然后,编译器会将代码中出现的每个 x 替换为文字 10.

Then, the compiler will replace every occurrence of x in the code with literal 10.

但是假设常量是在运行时初始化的:

But suppose the constant is initialized at run-time:

private final int x = getX(); // here getX() returns an integer value at run-time.

与编译时常量相比,会不会有任何性能下降(无论如何可以忽略不计)?

Will there be any performance drop (howsoever negligible it may be) compared to the compile-time constant?

另一个问题是下面的代码行:

Another question is whether the below line of code:

private int y = 10; // here y is not final

编译器是否以与编译时常量相同的方式处理?

is treated in same way as compile-time constant by the compiler?

最后,我从答案中了解到:

Finally, what I understand from the answers are:

  1. final static 表示编译时常量
  2. just final 表示它是一个常量,但在运行时初始化
  3. 只是 static 意味着在运行时初始化
  4. 没有 final 是一个变量,不会被视为常量.
  1. final static means compile-time constant
  2. just final means it's a constant but is initialized at run-time
  3. just static means initialized at run-time
  4. without final is a variable and wouldn't be treated as constant.

我的理解正确吗?

推荐答案

编译时常量必须为:

  • 宣布为最终版
  • 原始或字符串
  • 在声明中初始化
  • 用常量表达式初始化

所以 private final int x = getX(); 不是常数.

对于第二个问题 private int y = 10; 不是常量(在这种情况下是非最终的),因此优化器无法确定该值将来不会改变.所以它不能像常数值一样优化它.答案是:不,它与编译时常量的处理方式不同.

To the second question private int y = 10; is not constant (non-final in this case), so optimizer cannot be sure that the value would not change in the future. So it cannot optimize it as good as constant value. The answer is: No, it is not treated the same way as compile time constant.

这篇关于编译时常量和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆