Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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
}

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top