Clarification regarding traditional interpreter, compiler and JIT compiler/interpreter

后端 未结 2 788
孤城傲影
孤城傲影 2021-01-06 06:57

I\'m learning Java and the following things are a bit confusing for me. What I understood is:

  • Java Compiler → The Java compiler just conver

2条回答
  •  南方客
    南方客 (楼主)
    2021-01-06 07:58

    Disclaimer: Take all of this with a grain of salt; it's pretty oversimplified.

    1: You are correct in that the computer itself doesn't understand the code, which is why the JVM itself is needed. Let's pretend XY means "add the top two elements on the stack and push the result". The JVM would then be implemented something like this:

    for(byte bytecode : codeToExecute) {
        if (bytecode == XX) {
            // ...do stuff...
        } else if (bytecode == XY) {
            int a = pop();
            int b = pop();
            push(a+b);
        } else if (bytecode == XZ) {
            // ...do stuff...
        } // ... and so on for each possible instruction ...
    }
    

    The JVM has, in the computer's native machine code, implemented each individual instruction and essentially looks up each chunk of bytecode for how to execute it. By JITting the code, you can achieve large speedups by omitting this interpretation (i.e. looking up how each and every instruction is supposed to be handled). That, and optimization.

    2: The JIT doesn't really run the code; everything is still run inside the JVM. Basically, the JIT translates a chunk of bytecode into machine code when appropriate. When the JVM then comes across it, it thinks "Oh hey, this is already machine code! Sweet, now I won't have to carefully check each and every byte of this as the CPU understands it on its own! I'll just pump it through and everything will magically work on its own!".

    3: Yes, it is possible to pre-compile code in that way to avoid the early overhead of interpretation and JITting. However, by doing so, you lose something very valuable. You see, when the JVM interprets the code, it also keeps statistics about everything. When it then JITs the code, it knows how often different parts are used, allowing it to optimize it where it matters, making the common stuff faster at the expense of the rare stuff, yielding an overall performance gain.

提交回复
热议问题