简体   繁体   English

java.util.Collection具有最低的开销?

[英]java.util.Collection with the lowest overhead?

I'm calling a method in another API that accepts a java.util.Collection of objects. 我正在另一个API中调用一个接受java.util.Collection对象的方法。 I've looked at the method and it immediately copies everything in the collection into a new ArrayList before performing its task. 我查看了该方法,它会在执行任务之前立即将集合中的所有内容复制到新的ArrayList

This got me wondering: What is the absolute lowest overhead Java Collection that I can use to quickly assemble parameters for this method? 这让我想知道:我可以用来快速组装此方法的参数的绝对最低开销Java Collection是什么?

That depends on how it copies the elements, but if it creates the ArrayList -copy like this 这取决于它如何复制元素,但如果它像这样创建ArrayList -copy

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 . 然后它将通过inputCollection.toArray() ,它可能最好由ArrayList实现。

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(...) ). Arrays$ArrayList缺失,但可能是ArrayListArrays.asList(...) )的一个很好的替代品。

Update: I updated the original links to the new location of the project in github. 更新:我在github中更新了项目新位置的原始链接。 Take into account these metrics are several years old. 考虑到这些指标已有几年历史了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM