This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

collection.size() vs. array.length

 
paul wheaton
Trailboss
Pie
Posts: 21346
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the article at http://java.oreilly.com/news/javaperf_0900.html the advantages of not having collection.size() used in the for loop are pointed out. Would this apply equally to array.length?
 
Jack Shirazi
Author
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. Java arrays (e.g. char[], Object[], not collection objects) cannot change size. So the value is a constant for any one array, and the loop has a constant value to compare against. The problem with collection.size() is that it makes a method call for every iteration of the loop.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic