什么是字节码以及 JVM 如何处理它们

2022-01-16 00:00:00 jvm bytecode java

我多次听说 Java 实现了 JIT(即时)编译,其可跨平台移植的字节码被 JVM 解释".但是,我真的不知道字节码是什么,以及 JVM 在 Java 语言体系结构中的实际含义;我想了解更多关于他们的信息.

I heard many times that Java implemments JIT(just-in-time) compilation, and its bytecodes which are portable across platforms get "interpreted" by JVM. However, I don't really know what the bytecodes are, and what the JVM actually mean in Java language architecture; I would like to know more about them.

推荐答案

JVM(Java虚拟机)有一个指令集,就像一个真正的机器.该指令集的名称是 Java Bytecode.Java 虚拟机规范 中对其进行了描述.其他语言在执行前会被翻译成字节码,例如 ruby​​ 和 python.Java 的字节码处于相当低的级别,而 python 的字节码则更高.

The JVM (Java Virtual Machine) has an instruction set just like a real machine. The name given to this instruction set is Java Bytecode. It is described in the Java Virtual Machine Specification. Other languages are translated into a bytecode before execution, for example ruby and python. Java's bytecode is at a fairly low level while python's is much more high level.

解释和 JIT 编译是执行字节码的两种不同策略.解释一次处理一个字节码,对每条指令中编码的虚拟机状态进行更改.JIT 编译将字节码翻译成主机平台的本机指令,执行等效操作.

Interpretation and JIT compilation are two different strategies for executing bytecode. Interpretation processes bytecodes one at a time making the changes to the virtual machine state that are encoded in each instruction. JIT compilation translates the bytecode into instructions native to the host platform that carry out equivalent operations.

解释通常启动很快,但在执行过程中很慢,而 JIT 的启动开销更大,但之后运行得更快.现代 JVM 使用解释和 JIT 技术的组合来获得两者的好处.当 JIT 在后台翻译字节码时,首先解释字节码.一旦 JIT 编译完成,JVM 就会切换到使用该代码而不是解释器.有时 JIT 编译可以产生比用于 C 和 C++ 的提前编译更好的结果,因为它更具动态性.JVM 可以跟踪代码被调用的频率以及通过代码的典型路径是什么,并使用这些信息在程序运行时生成更高效的代码.JVM 可以切换到这个新代码,就像它最初从解释器切换到 JIT 代码一样.

Interpretation is generally quick to start but slow during execution, while JIT has more startup overhead but runs quicker afterwards. Modern JVMs use a combination of interpretation and JIT techniques to get the benefit of both. The bytecode is first interpreted while the JIT is translating it in the background. Once the JIT compilation is complete, the JVM switches to using that code instead of the interpreter. Sometimes JIT compilation can produce better results than the ahead-of-time compilation used for C and C++ because it is more dynamic. The JVM can keep track of how often code is called and what the typical paths through the code are and use this information to generate more efficient code while the program is running. The JVM can switch to this new code just like when it initially switches from the interpreter to the JIT code.

就像有其他语言可以编译为本机代码一样,例如 C、C++、Fortran;有其他语言的编译器可以输出 JVM 字节码.一个例子是 scala 语言.相信groovy和jruby也可以转换成java字节码.

Just like there are other languages that compile to native code, like C, C++, Fortran; there are compilers for other languages that output JVM bytecode. One example is the scala language. I believe that groovy and jruby can also convert to java bytecode.

相关文章