Thursday, August 15, 2013

Just In Time Compiler

We discussed in my previous blog about how JVM makes java program platform independent but "everything in life comes at a cost". Java's two pass execution to achieve this platform independence,The process of Java Compiler first compiling the java source code into byte code and then the JVM interpreting the .class files into native processor does take a toll on execution time of a typical Java program. Thus java programs run always slower than the native compiled  languages like C. And adding to it interpreting the .class file's byte code instructions made the  Java programs really very slow.

So a lot of effort is and was invested on improving the execution speed of java programs. One of the breakthroughs of this effort is Just in Time Compilation.

Now before moving to this topic a general question most of us will surely have is :

If interpreter is slow why not compile Byte code first and then run?
   Please remember that we are not concerned about the programmer on how much time is spent on compiling a java code. All we are focused is about the user who runs our program and JVM comes into picture when JRE on a native platform is trying to run our program. Imagine how much time it may take to compile a whole bunch of .class files first and then load and start running it. The user may sleep while this happen. And the program loading will be terrible. 

So we must strike a right balance between this interpreting and compiling. And the answer as for as now with its own limitation which we will not cover here is Just in Time compilers.

The concept is derived from an inventory strategy companies employ to increase efficiency and decrease waste by receiving goods only when they are needed in production process there by reducing inventory costs.

Not all of code is used in a run cycle of a program. For example the error handling or certain conditional branching never happens in a particular run time of a program . So why compile entire code. 

"So JIT compilers of a JVM will compile the byte code into machine code only when it is referenced. And then JVM will execute it into native hardware. Functions are the smallest units and are compiled only when they are referenced."

Though JIT looks concept wise simple there are lot of pitfalls of JIT especially during compile optimizations. This is not covered in this discussion. However people interested can go through the below post.

Hope things are clear. Please share your comments on this article.

No comments:

Post a Comment