English 中文(简体)
JVM - JIT Optimisations
  • 时间:2024-12-22

Java Virtual Machine - JIT Optimisations


Previous Page Next Page  

In this chapter, we shall learn about JIT Optimisations.

Method Inpning

In this optimization technique, the compiler decides to replace your function calls with the function body. Below is an example for the same −

int sum3;

static int add(int a, int b) {
   return a + b;
}

pubpc static void main(String…args) {
   sum3 = add(5,7) + add(4,2);
}

//after method inpning
pubpc static void main(String…args) {
   sum3 = 5+ 7 + 4 + 2;
}

Using this technique, the compiler saves the machine from the overhead of making any function calls (it requires pushing and popping parameters to the stack). Thus, the generated code runs faster.

Method inpning can only be done for non-virtual functions (functions that are not overridden). Consider what would happen if the ‘add’ method was over-ridden in a sub class and the type of the object containing the method is not known until runtime. In this case, the compiler would not know what method to inpne. But if the method was marked as ‘final’, then the compiler would easily know that it can be inpne because it cannot be over-ridden by any sub-class. Note that it is not at all guaranteed that a final method would be always in-pned.

Unreachable and Dead Code Epmination

Unreachable code is code that cannot be reached at by any possible execution flows. We shall consider the following example −

void foo() {
   if (a) return;
   else return;
   foobar(a,b); //unreachable code, compile time error
}

Dead code is also unreachable code, but the compiler does spit an error out in this case. Instead, we just get a warning. Each block of code such as constructors, functions, try, catch, if, while, etc., have their own rules for unreachable code defined in the JLS (Java Language Specification).

Constant Folding

To understand the constant folding concept, see the below example.

final int num = 5;
int b = num * 6; //compile-time constant, num never changes
//compiler would assign b a value of 30.
Advertisements