0

Does the Java compiler apply some transformations to optimize method calls? Or does it always generate a faithful representation of the source with simple optimizations like removing dead code?

Specifically if we have the below example:

public static void main(String[] args) {
    System.out.println(foo());
    System.out.println(foo());
    System.out.println(foo());
    System.out.println(bar());
    System.out.println(bar());
    System.out.println(bar());
}

public static int foo() {
    int[] arr = {1, 2, 3, 4};
    return arr[0];
}

public static int bar() {
    return 10;
}

Does the compiler attempt to replace the call to bar (or even possibly foo) with a call to print the integer 10?

public static void main(String[] args) {
    System.out.println(1);
    System.out.println(1);
    System.out.println(1);
    System.out.println(10);
    System.out.println(10);
    System.out.println(10);
}

I know of a method called inlining that can lead to such transformations, but I was wondering if the Java compiler (at least the javac of the Oracle JDK) applies it, or if it's always deferred to the JVM.

M A
  • 71,713
  • 13
  • 134
  • 174
  • 3
    The answer is 'it depends'. Java has a [JIT](http://en.wikipedia.org/wiki/Just-in-time_compilation), as well as doing some manner of optimizations when turning the source into byte-code. So basically, as long as it doesn't change the observable behavior of the code, Java can really do any kind of optimization at any time. – aruisdante Oct 22 '14 at 20:06
  • See: http://stackoverflow.com/questions/2096361/are-there-inline-functions-in-java – aruisdante Oct 22 '14 at 20:08
  • And: http://stackoverflow.com/questions/8256202/how-does-the-java-jit-compiler-optimize-my-code – aruisdante Oct 22 '14 at 20:08

1 Answers1

1

This type of optimization is called constant folding.

These (and other optimizations) that do not affect the observable result of programs are allowed by Java's specification.

However, whether or not a given compiler actually performs these optimizations is entirely up to the implementation.

Luke Willis
  • 8,429
  • 4
  • 46
  • 79