What are the advantages of using Virtual Machine compilation (eg. JVM) over natively compiled languages?

后端 未结 8 1163
既然无缘
既然无缘 2020-12-24 13:26

I\'ve heard that the advantage of java is that people can write code, compile it for the JVM, and run it anywhere. Each person just needs a JVM app for their platform.

8条回答
  •  佛祖请我去吃肉
    2020-12-24 14:22

    ... where everybody has a compiler specific for their platform. So the advantage isn't explained by that.

    Porting code written in for example C or C++ is almost always much more involved than simply recompiling the code. It's certainly not something that an average, non-developer computer user can do easily. Code written in compiled languages is very often written against the API of a specific operating system (the Win32 API, for example) and so it cannot be compiled on other operating systems easily.

    Java bytecode runs on any platform where there is a Java runtime environment available. The code doesn't need to be recompiled. Ofcourse you can write operating-system specific code in Java, but Java's standard library, and the many free libraries available on the web, provide a very rich cross-platform environment.

    Besides portability, running on a virtual machine has other advantages. Java uses a JIT compiler to compile Java bytecode to native machine code at runtime. The JIT compiler can do sophisticated optimizations for the specific CPU that the program is running on and it can use profiling information that wouldn't be available to an ahead-of-time compiler - in principle, a JIT compiler can therefore produce more optimal code than a "normal" compiler.

    Besides the Java VM, there are other virtual machines. For example, Microsoft .NET contains the CLR (Common Language Runtime) and there's also LLVM, which has front-ends for many different languages including C and C++ (and which is supposed to bring the advantages of JIT compilation also to C and C++).

提交回复
热议问题