…
“Premature optimization is the root of all evil”.
Don’t think about optimizing such things, JIT will do everything to make your code as fast as possible.
Java’s JIT inlines things very aggressively – it’s quite likely the call overhead is zero because there is no call.
Don’t think about performance overhead of things like multidimensional arrays, method calls (especially static method calls), the most efficient way to do anything is just to keep it simple and clean.
HotSpot is very aggressive at inlining. Additionally field accessors have a special cased optimization path.
@Mac70: I read this as a “how does it work” question.
??? From B, you simply use “bar” directly.
public class AAA
{
protected int bar = 2;
protected int getBar() { return 2; }
}
public class BBB extends AAA
{
public static void main(String[] args)
{
BBB bbb = new BBB();
bbb.doSomething();
}
private void doSomething()
{
System.out.println(bar);
}
}
To the best of my limited understanding, the following methodology is of mixed usefulness, but you can try putting the test cases in loops and executed them a million or so times, and check the elapsed time. I’d try to at least do something to have each iteration of the loop be slightly different. For example, set a variable to a different value each time:
public void doSomethingTest()
{
long startTime = System.nanoTime();
for (int i = 0; i < 1000000; i++)
{
bbb.doSomething(i); // put within doSomething: int foo = i;
}
long endTime = System.nanoTime();
System.out.println("elapsed time: " + (endTime - startTime) );
}
I find it helps to run these multiple times, as each iteration will probably have a different result. Also, have to keep in mind that Java responds differently depending on when it is running from bytecode or memory, and the degree of caching can depend on whatever else is happening in the code. There is also no guarantee that elapsed times will be consistent across various OS / JVM combinations.
I don’t know the actual answer, but I suspect, along with the others, that the differences you are asking about here are either non-existent or of extremely low relevance. However, there’s been a number of times when I’ve done these sorts of tests and been surprised! So I wouldn’t discourage taking the five or ten minutes needed to occasionally run a test like the above.
I’m trying to think about any resources that go into depth specifically about Java compilation and execution. The only one I know about is “Java Concurrency in Practice” (Goetz) which has a section on performance testing and a chapter on the Java Memory Model which gets into compiler details, but the book is pretty advanced (imho).