• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

collection.size() vs. array.length

 
paul wheaton
Trailboss
Pie
Posts: 21387
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