assuming no compiler optimizations
When you use
for(int i = 0; i < 1000; i++) {
foo.getBar() // then do something with it
}
Your code will go to your instance referred by foo
, execute its getBar()
method, which will then return an instance/value of whatever it is supposed to return. This will be done for each and every one of your 1000 executions of that loop. After each execution is done, the value returned by getBar()
will have to be garbage collected.
However, when you use:
Bar bar = foo.getBar();
for(int i = 0; i < 1000; i++) {
bar // then do something with it
}
You get the value of foo.getBar()
only once, outside your loop and store a copy of it locally. This local copy is then used in the loop 1000 times.
The second option is more efficient because your foo
instance's getBar()
method is called only once, instead of a thousand times. This means you don't execute the code in the getBar()
method 1000 times, which is obviously worse than executing it once.
These are all really micro optimizations. Unless you are doing some real heavy lifting in getBar()
, this won't have a noticeable effect. In a lot of cases, compiler optimizations will turn both of these into the exact same Bytecode, so you wouldn't worry about it anyways.