Difference in performance for simple and for iterator

5

I have a list of clients and on a certain screen the user can search and edit the clients of the list that is very extensive, comparing these two examples what would be the best to work?

Example 1:

for (int i = 0, tamI = listAll.size(); i< tamI;i++)
           if (listAll.get(i).getNome().toLowerCase().startsWith(query.toLowerCase()))
                listResult.add(listAll.get(i));

Example 2:

for (Cliente item : listAll)
            if(item.getNome().toLowerCase().startsWith(query.toLowerCase()))
                listResult.add(item);
    
asked by anonymous 23.08.2017 / 15:45

1 answer

2

It depends a little on what this ListAll is, it can be several types of structure, each with a compromise of different complexity. It has collection that calculation of size() can be huge and an iteration can be absurdly faster. But considering that size() has complexity O (1) low the difference should be very little, often varying according to other circumstances.

So, use the more readable flow control structure that best shows intent and avoiding more errors should be preferred, so the one that uses the iterator ( for each ) would be better .

It may be that some case has a better performance with for simple, but would have to analyze case by case. Do not assume you know which will be faster, can break the face. There are optimizations that can give different result than the intuitive one. And it can change according to the compiler version or the * framework.

    
23.08.2017 / 16:18