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.