More efficient way to use "expression" in improved "for" cycles

-1

In the following ways, which one is the most efficient?

...
//assumindo que o método pegaListaPessoas() pesquisa na base de dados todos as pessoas
for (Pessoa pAux : pegaListaPessoas())
{
    //executo alguma coisa
}

or:

...
//assumindo que o método pegaListaPessoas() pesquisa na base de dados todos as pessoas
List<Pessoa> pessoas = pegaListaPessoas();
for (Pessoa pAux : pessoas)
{
    //executo alguma coisa
}
    
asked by anonymous 09.09.2014 / 10:59

1 answer

5

Always the best way for you to find out is to measure. What may seem one thing in theory may prove to be another in a particular specific case. In fact this can be considered premature optimization .

If you ask random people on the internet who do not know an implementation, the exact conditions of your application and the performance requirements, do not expect something very precise.

I can not respond with absolute certainty because I do not know the implementation of pegaListaPessoas() , I do not know the implementation of what it returns up to because I even know what it returns. But you could kick with a good chance of success that makes no difference.

What does this method return? A Iterable that scans a cached list of database contents data? And the implementation of this interface is List ? Or is it your own implementation where next() will query the database? If there is a performance problem, it may be in a different place than imagined.

Roughly implementations should be compiled for the equivalent of

for (Iterator<Pessoa> i = pegaListaPessoas().iterator(); i.hasNext(); i.next()) {

and

List<Pessoa> pessoas = pegaListaPessoas();
for (Iterator<Pessoa> i = pessoas.iterator(); i.hasNext(); i.next()) {

In the first case, it calls the pegaListaPessoas() the first time , receives a iterator from the list created by the method, all this before the first ; and every step it takes the next iteration item with next() (after the second ; ) and check if there is any more item with hasNext() . Only the last two are executed in each step. Initialization is performed only once.

The only difference in the second case is that the list is generated before starting the loop .

Actually if you visualize this as a while it becomes more obvious:

Iterator<Pessoa> i = pegaListaPessoas().iterator();
while (i.hasNext()){
     Pessoa p = i.next();
}

and

List<Pessoa> pessoas = pegaListaPessoas();
Iterator<Pessoa> i = pessoas.iterator();
while(i.hasNext()){
     Pessoa p = i.next();
}

Do you understand that the secret is iterator ? And as far as I know a loop for in can only run over collections that implement the Iterable interface (perhaps with the exception of array , String and other types that language be aware of the operation and use the index directly).

    
09.09.2014 / 12:15