java.util.Collection with the lowest overhead?

1.1k views Asked by At

I'm calling a method in another API that accepts a java.util.Collection of objects. I've looked at the method and it immediately copies everything in the collection into a new ArrayList before performing its task.

This got me wondering: What is the absolute lowest overhead Java Collection that I can use to quickly assemble parameters for this method?

3

There are 3 answers

3
aioobe On BEST ANSWER

That depends on how it copies the elements, but if it creates the ArrayList-copy like this

new ArrayList<Something>(inputCollection);

or if it does

someCopy.addAll(inputCollection);

then the it will go through the inputCollection.toArray() which is probably best implemented by ArrayList.

0
irreputable On

It depends on your source data.

If your source data is already an array, and the array will not be used by others, the fastest way is to have a thin wrapper:

final Object[] source = ...

Collection colllection = new AbstractCollection(){
    public Object[] toArray(){ return source; }
    // other methods don't matter
}
0
superfav On

If you are talking about memory footprint, take a look at this table in memory-measurer. Arrays$ArrayList is missing, but could be a good alternative to ArrayList (Arrays.asList(...)).

Update: I updated the original links to the new location of the project in github. Take into account these metrics are several years old.