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

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

问题描述

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. 只需 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.

我的理解是否正确?

推荐答案

编译时间常数必须为:


  • 宣布最终

  • 原语或字符串

  • 在声明中初始化

  • 使用常量表达式初始化

  • declared final
  • primitive or String
  • initialized within declaration
  • initialized with constant expression

所以私人决赛int x = getX(); 不是常数。

到secon d问题 private int y = 10; 不是常量(在这种情况下是非final),因此优化器无法确定该值将来是否会发生变化。所以它不能像恒定值那样优化它。答案是:不,它的处理方式与编译时间常数不同。

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天全站免登陆