java - 文字的算术运算是在编译时还是运行时计算的?

标签 java

我有以下几点:

double timeInMinutes = (double) timeInMilliseconds / (1000 * 60);

操作 (1000 * 60) 是在编译时还是在运行时完成的?换句话说,上面的代码片段在运行时是否存在性能差异:

double timeInMinutes = (double) timeInMilliseconds / 60000;

编辑:我的问题与 Will the Java compiler precalculate sums of literals? 不同,因为我在算术运算中混合使用变量和文字。这是一个很小的区别,但正如@TagirValeev 在评论中指出的那样( Are arithmetic operations on literals calculated at compile time or run time? ),有些文字即使可以预编译也没有预编译。

最佳答案

根据 JLS §15.2 - Forms of Expressions

Some expressions have a value that can be determined at compile time. These are constant expressions (§15.28).

*、/和 % 等乘法运算符属于常量表达式,因此将在编译时确定。

@SergeyMorozov 比我更快地编写和获得字节码证明(#2 = Integer 60000),但这是实际证明,以上是理论/官方声明:

尝试使用 1000 * 6060000 在您的最后生成字节码,您将看到相同的字节码指令,因此会有相同的运行时性能.

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
}

关于java - 文字的算术运算是在编译时还是运行时计算的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33040680/

相关文章:

java - 当来自其他包的类时方法调用失败

java - 字符串上一个最后一个索引

Java代码找不到nlsxbe.dll的依赖库

java - 将基类对象转换为扩展基类的类时出现 ClassCastException

java - 无法使用 servlet 3 可插入性功能将 Jersey 2.16 集成到 Tomcat 8.0.12

java - 使用 hadoop 错误设置获取 JAVA_HOME

java - 如何编写java代码REST Assured代码来获取授权 token ?

java - 使用 Micrometer 将 New Relic 与 Spring Boot 集成

java - 如何找到运行中的 JVM 附带的 Java 代理列表?

java - org.apache.commons.lang3.time.DateFormatUtils.format() 线程安全吗?