Why I'm asking:
I wanted to know it there is any optimization going on at the compiler side that would make one or the other method to return preferable. Since I have read this post that python does not optimize the method to run faster.
The example:
I've declared 2 methods that deliver the same value. But barA
returns it via an internal field declaration.
public class Foo {
public int barA(){
int a = 1;
return a;
}
public int barB(){
return 1;
}
}
The tests:
public class TestFoo {
Foo foo = new Foo();
Method methodA = foo.getClass().getMethod("barA");
Method methodB = foo.getClass().getMethod("barB");
public TestFoo() throws NoSuchMethodException {
}
@Test
public void methodA() throws Exception {
assertTrue(Integer.TYPE.equals(methodA.getReturnType()));
}
@Test
public void methodB() throws Exception {
assertTrue(Integer.TYPE.equals(methodB.getReturnType()));
}
@Test
public void equalsSame() throws Exception{
assertEquals(foo.barA(), foo.barB());
}
}
The results:
The tests showed that I'm in fact dealing with the same value and return type in both methods.
Disclaimer: This picture is not meant to highlight the stop watch, junit runs for each method, as it's in no way linked to the compiler optimization I'm asking about.
The question:
Does Java actually try to optimize away "useless" field declarations in order to execute faster?
I was not able to find a question addressing this.
Using:
- jdk 1.8.0_121
- junit 4.10