Performance difference from for simple and for iterator

Asked

Viewed 121 times

5

I have a list of customers and on a certain screen the user can do a search and edit the clients of the list that is quite extensive, comparing these two examples which 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);
  • 1

    Related : https://answall.com/questions/63005/qual-possuí-um-performant-bestfor-ou-foreachrange

  • 1
  • 1

    This site is great for comparing Javascript/Jquery methods : https://jsperf.com/

  • 5

    @Bruno but no Javascript/Jquery code here!

  • I am using the second example, because it is an implementation of the language I believe it is optimized for these situations

  • 1

    @Gabriellocalhost Did the answer resolve what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?

Show 1 more comment

1 answer

2


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

Therefore, use the most readable flow control structure, which better shows the intention and avoids more errors should be preferred, so the one that uses the iterator (for each) would be better.

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

  • Listall has an average of about 3000 records or more

  • 1

    @Gabriellocalhost edited to show that size does not matter

Browser other questions tagged

You are not signed in. Login or sign up in order to post.