Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Java faster when using a JIT vs. compiling to machine code?

Tags:

java

jit

I have heard that Java must use a JIT to be fast. This makes perfect sense when comparing to interpretation, but why can't someone make an ahead-of-time compiler that generates fast Java code? I know about gcj, but I don't think its output is typically faster than Hotspot for example.

Are there things about the language that make this difficult? I think it comes down to just these things:

  • Reflection
  • Classloading

What am I missing? If I avoid these features, would it be possible to compile Java code once to native machine code and be done?

like image 840
Adam Goode Avatar asked Dec 10 '09 04:12

Adam Goode


People also ask

What is the advantage of compiling Java source code using a JIT?

Advantages of just-in-time compilationJIT compilers need less memory usage. JIT compilers run after a program starts. Code optimization can be done while the code is running. Any page faults can be reduced.

Why is JIT faster than interpreter?

The JIT-compiled code is actually running directly on the bare metal whereas interpreted code has to be continually reinterpreted by the interpreter. The interpreter is no longer having to reprocess and reprocess the byte code.

Does JIT improve the performance of Java applications?

The JIT compiler helps improve the performance of Java programs by compiling bytecodes into native machine code at run time. The JIT compiler is enabled by default. When a method has been compiled, the JVM calls the compiled code of that method directly instead of interpreting it.


1 Answers

A JIT compiler can be faster because the machine code is being generated on the exact machine that it will also execute on. This means that the JIT has the best possible information available to it to emit optimized code.

If you pre-compile bytecode into machine code, the compiler cannot optimize for the target machine(s), only the build machine.

like image 173
Andrew Hare Avatar answered Oct 03 '22 18:10

Andrew Hare