user1454672
user1454672

Reputation: 21

Which one is more efficient? Caching method call result used in for loop

The difference is probably miniscule or doesn't exist, but which one is more efficient and why?

int nItems = param.getItemList().size();
for (...) {
    if (nitems == 1) doSomething();
}

or

for (...) {
    if (param.getItemList().size() == 1) doSomething();
}  

Upvotes: 2

Views: 354

Answers (4)

Óscar López
Óscar López

Reputation: 235984

In theory the first one will be faster (have you profiled it? you should!), because it pulls a frequently used method call outside of the loop. However, given enough time the JIT compiler might optimize/inline the method call making both solutions indistinguishable in terms of performance.

Such micro-micro-optimizations are not worth the effort, better aim for the solution that it's clearer and simpler to understand. Which IMHO happens to be the first one.

Upvotes: 8

mlorbetske
mlorbetske

Reputation: 5649

The first one, because you don't need to make the two calls for every iteration of the loop

Upvotes: 0

FThompson
FThompson

Reputation: 28687

The first is more efficient because the method need not be invoked several times. However, as both getItemList() and size() seem to be accessors, the difference will be miniscule.

Upvotes: 0

Carl Manaster
Carl Manaster

Reputation: 40336

It is more efficient to make the method call outside the loop. Sometimes it may even matter. The one circumstance under which the second approach might be more efficient is if the conditions of the for loop resulted in the loop being skipped entirely.

Upvotes: 1

Related Questions