文字的算术运算是在编译时还是运行时计算的? [英] Are arithmetic operations on literals calculated at compile time or run time?
问题描述
我有以下内容:
double timeInMinutes = (double) timeInMilliseconds / (1000 * 60);
操作是否为(1000 * 60)
在编译时或运行时完成?换句话说,在上面的代码片段和运行时间之间是否存在性能差异:
Is the operation (1000 * 60)
done at compile time or at run time? In other words, are there performance differences during run time between the code snippet above and:
double timeInMinutes = (double) timeInMilliseconds / 60000;
编辑:我的问题与 Java编译器是否会预先计算文字的总和?,因为我在算术运算中混合了变量和文字的使用。这是一个小小的差异,但正如@TagirValeev在评论中指出的那样(对文字的算术运算是在编译时还是运行时计算的?),有些文字虽然可以预先编译,但有些文字不会被预编译。
my question is different from Will the Java compiler precalculate sums of literals?, as I'm mixing the use of variables and literals in the arithmetic operations. It's a small difference, but as @TagirValeev noted in the comments (Are arithmetic operations on literals calculated at compile time or run time?), there are instances where some literals aren't pre-compiled even though they could be.
推荐答案
有些表达式的值可以确定在编译时。
这些是常量表达式(§15.28)。
Some expressions have a value that can be determined at compile time. These are constant expressions (§15.28).
多重运算符,如 *,/和%
属于常量表达式,因此它将在编译时确定。
Multiplicative operators like *, /, and %
falls under constant expressions, so it would be determined at compile time.
@SergeyMorozov比我更快写入并获得字节码证明(#2 =整数60000
)但这里是实际证据,上面是理论/官方声明:
@SergeyMorozov was faster than me to write and get byte code proof (#2 = Integer 60000
) but here is the practical proof and above is theoretical/official statement:
尝试使用 1000 * 60
和 60000
生成字节代码,您将看到相同的字节代码指令,因此会有相同的运行时性能。
Try generating byte code at your end as well using 1000 * 60
and 60000
, and you will see same byte code instructions, and hence there would be same runtime performance.
Java类:
public class Test {
public static void main(String[] args) {
int compileTest = 1000 * 60;
}
}
字节代码:
Classfile /E:/Test.class
Last modified Oct 9, 2015; size 265 bytes
MD5 checksum fd115be769ec6ef7995e4c84f7597d67
Compiled from "Test.java"
public class Test
SourceFile: "Test.java"
minor version: 0
major version: 51
flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
#1 = Methodref #4.#13 // java/lang/Object."<init>":()V
#2 = Integer 60000
#3 = Class #14 // Test
#4 = Class #15 // java/lang/Object
#5 = Utf8 <init>
#6 = Utf8 ()V
#7 = Utf8 Code
#8 = Utf8 LineNumberTable
#9 = Utf8 main
#10 = Utf8 ([Ljava/lang/String;)V
#11 = Utf8 SourceFile
#12 = Utf8 Test.java
#13 = NameAndType #5:#6 // "<init>":()V
#14 = Utf8 Test
#15 = Utf8 java/lang/Object
{
public Test();
flags: ACC_PUBLIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
LineNumberTable:
line 1: 0
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=2, args_size=1
0: ldc #2 // int 60000
2: istore_1
3: return
LineNumberTable:
line 3: 0
line 4: 3
}
这篇关于文字的算术运算是在编译时还是运行时计算的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!