简体   繁体   English

在java中toArray与stream.toArray有任何性能差异

[英]Is there any performance difference in toArray vs stream.toArray in java

I need to convert a list of ids to array of ids. 我需要将id列表转换为id数组。 I can do it in many ways but not sure which one should be used. 我可以在很多方面做到这一点,但不确定应该使用哪一个。

Say, 说,

1. ids.stream().toArray(Id[]::new)
2. ids.toArray(new Id[ids.length])

Which one is more efficient and why? 哪一个更有效率,为什么?

java-11 introduced Collection::toArray that has this implementation: java-11引入了具有此实现的Collection::toArray

default <T> T[] toArray(IntFunction<T[]> generator) {
    return toArray(generator.apply(0));
}

To make it simpler in your case, it is actually doing : ids.toArray(new Id[0]) ; 为了使你的情况更简单,它实际上是在做: ids.toArray(new Id[0]) ; that is - it is not specifying the total expected size. 也就是说 - 它没有指定总预期大小。

This is faster than specifying the size and it's non-intuitive; 这比指定大小更快,而且不直观; but has to do with the fact that if the JVM can prove that the array that you are allocating is going to be overridden by some copying that is immediately followed, it does not have to do the initial zeroing of the array and that proves to be faster then specifying the initial size (where the zeroing has to happen). 但是,如果JVM可以证明你正在分配的数组将被一些紧接着的复制覆盖,那么它就不需要对数组进行初始归零,而且证明是然后指定初始大小(必须发生归零)。

The stream approach will have (or try to guess an estimate) an initial size that the stream internals will compute, because: 流方法将具有(或尝试猜测估计)流内部将计算的初始大小,因为:

 ids.stream().toArray(Id[]::new)

is actually: 实际上是:

 ids.stream().toArray(size -> Id[size]);

and that size is either known or estimated, based on the internal characteristics that a Spliterator has. 根据Spliterator的内部特征,该size是已知的或估计的。 If the stream reports SIZED characteristic (like in your simple case), then it's easy, size is always known. 如果流报告SIZED特征(就像你的简单情况一样),那么它很容易, size总是已知的。 On the other hand if this SIZED is not present, stream internals will only have an estimate of how many elements will be present and in such a case, an hidden new collection will be used to capture elements, called SpinedBuffer . 另一方面,如果不存在此SIZED ,则流内部将仅估计将存在多少元素,并且在这种情况下,将使用隐藏的新集合来捕获元素,称为SpinedBuffer

You can read more here , but the approach ids.toArray(new Id[0]) will be the fastest. 你可以在这里阅读更多内容,但方法ids.toArray(new Id[0])将是最快的。

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

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