Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Small (1-10 Items) Instance-Level Collections in Java

While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc).

class Foo
{
  ArrayList<Bar> bars = new ArrayList<Bar>(10);
}

A part of me keeps nagging at me that it's wasteful to use complex dynamic collections for something this small in size. Is there a better way of implementing something like this? Or is this the norm?

Note, I'm not hit with any (noticeable) performance penalties or anything like that. This is just me wondering if there isn't a better way to do things.

like image 735
Al. Avatar asked Sep 11 '08 17:09

Al.


1 Answers

The ArrayList class in Java has only two data members, a reference to an Object[] array and a size—which you need anyway if you don't use an ArrayList. So the only advantage to not using an ArrayList is saving one object allocation, which is unlikely ever to be a big deal.

If you're creating and disposing of many, many instances of your container class (and by extension your ArrayList instance) every second, you might have a slight problem with garbage collection churn—but that's something to worry about if it ever occurs. Garbage collection is typically the least of your worries.

like image 170
John Calsbeek Avatar answered Sep 21 '22 00:09

John Calsbeek