1

Which is the faster collection and with the smaller memory foot print that I could use to store some values to be iterated in an after moment? (It doesn't need to be ordered)

Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
  • http://stackoverflow.com/questions/629804/what-is-the-most-efficient-java-collections-library duplicate? – CosminO May 18 '12 at 09:20
  • doesn't matter, could be duplicated... but I want to use native java – Francisco Spaeth May 18 '12 at 09:21
  • @user1001027: I think it would be good if you add more details to your question: What sort of data do you want to add to the collection? How often you want to retrieve (get) an item? Are items deleted from the collection? – Helium May 18 '12 at 09:51
  • @Ameoo, no that question asks which collection library, this asks which native collection. I think this is a good question, poorly asked. – Tom Nov 06 '12 at 17:36

2 Answers2

1

This heavily depends on use case. That's why there's so many Collections, after all! Every one is good for a different thing.

Most importantly - Collection of what do you need? Is there any other action you'll do with it other than iterating? How many elements will it store? Will some of the elements be duplicated? Are there any performance-wise or memory-wise limitations? Without this information, we can give you only general answers.


The most general approach would be to use an array. Seriously. If you want to save memory, use arrays.

If that's not an option, then ArrayList is your best choice, since it uses arrays internally and is the most memory-efficient Collection in general (together with ArrayDeque, I think). It preallocates some space and gets twice as big every time it's filled up. Therefore, try to construct it with the right number of slots so there's no redundant space used.

If you're looking for something particular, you can use these:

  • to store bits, use BitSet
  • to store primitives, use Trove
  • if many of the elements will be present more than once in the Collection, you might want to try some Bag implementation, namely HashBag; or Multiset
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
0

This largely depends on the use case.

Does it need to be a collection? Not just an array? I would go with a LinkedList as it doesn't pre-allocate room like an ArrayList or Vector (shudder) does.

adarshr
  • 61,315
  • 23
  • 138
  • 167
Ewald
  • 5,691
  • 2
  • 27
  • 31
  • 2
    the `LinkedList` ist however not at all memory-efficient... especially on 64-bit platforms. – Lucero May 18 '12 at 09:24
  • I was thinking of faster to add and quick to iterate over. But yes, on 64-bit platforms it becomes an issue, good point. – Ewald May 18 '12 at 09:50