Win a copy of Spark in Action this week in the Open Source Projects forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Which is fastest way to iterate through a collection?

 
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We can iterate thru a collection using For loop or While loop or even iterator.

What are the pros and cons of using each way to iterate.

thanks
dra
 
lowercase baba
Posts: 12869
62
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Worrying about what is fastest is the wrong approach. You should instead work towards writing the simplest, cleanest code you can.

Generally speaking, if you know exactly how many times you want to do something, you would use a for loop. If you don't, you'd use a while loop. You would use a for-each loop if you have a collection where that would work.
 
Marshal
Posts: 67413
173
Mac Mac OS X IntelliJ IDE jQuery Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

fred rosenberger wrote:Worrying about what is fastest is the wrong approach. You should instead work towards writing the simplest, cleanest code you can.



That's important enough to immortalize:



 
If you believe you can tell me what to think, I believe I can tell you where to go. Go read this tiny ad!
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic