只要存在合适的虚拟机,将程序编译为字节码而不是本机代码就可以实现一定程度的可移植性。
但我有点想知道,为什么要推迟编译呢?为什么不在安装应用程序时简单地编译字节码呢?
如果这样做了,为什么不将其应用于直接编译为本机代码的语言呢?将它们编译为中间格式,随安装程序分发“JIT”编译器并在目标计算机上编译它。
我唯一能想到的是运行时优化。这是安装时唯一无法完成的主要事情。想法?
Compiling a program to bytecode instead of native code enables a certain level of portability, so long a fitting Virtual Machine exists.
But I'm kinda wondering, why delay the compilation? Why not simply compile the byte code when installing an application?
And if that is done, why not adopt it to languages that directly compile to native code? Compile them to an intermediate format, distribute a "JIT" compiler with the installer and compile it on the target machine.
The only thing I can think of is runtime optimization. That's about the only major thing that can't be done at installation time. Thoughts?
发布评论
评论(3)
通常它是预编译的。例如,考虑使用 NGEN 预编译 .NET 代码。
不预编译所有内容的原因之一是可扩展性。考虑那些允许使用反射在运行时加载附加代码的语言。
Often it is precompiled. Consider, for example, precompiling .NET code with NGEN.
One reason for not precompiling everything would be extensibility. Consider those languages which allow use of reflection to load additional code at runtime.
一些 JIT 编译器(例如 Java HotSpot)使用基于类型反馈的内联。他们跟踪程序中实际使用的类型,并基于他们之前看到的就是他们稍后会看到的假设来跟踪内联函数调用。为了使其发挥作用,他们需要通过多次“热循环”迭代来运行程序,以便了解使用了哪些类型。
此优化在安装时完全不可用。
Some JIT Compilers (Java HotSpot, for example) use type feedback based inlining. They track which types are actually used in the program, and inline function calls based on the assumption that what they saw earlier is what they will see later. In order for this to work, they need to run the program through a number of iterations of its "hot loop" in order to know what types are used.
This optimization is totally unavailable at install time.
字节码已被编译,就像 C++ 代码已被编译一样。
此外,JIT 编译器(即 .NET 和 Java 运行时)是庞大且动态的;而且您无法在程序中预见应用程序使用哪些部分,因此您需要整个运行时。
此外,人们还必须认识到,针对虚拟机的语言与针对裸机的语言具有截然不同的设计目标。
以 C++ 与 Java 为例。
编辑:正如delnan正确指出的那样; JIT 和类似技术虽然对字节码性能非常有益,但在安装时可能不可用。此外,为虚拟机进行编译与编译为本机代码有很大不同。
The bytecode has been compiled just as well as the C++ code has been compiled.
Also the JIT compiler, i.e. .NET and the Java runtimes are massive and dynamic; And you can't foresee in a program which parts the apps use so you need the entire runtime.
Also one has to realize that a language targeted to a virtual machine has very different design goals than a language targeted to bare metal.
Take C++ vs. Java.
EDIT: As delnan points out correctly; JIT and similar technologies, though hugely benificial to bytecode performance, would likely not be available at install time. Also compiling for a VM is very different from compiling to native code.