Collection.toArray() vs Collection.stream().toArray()

有些话、适合烂在心里 提交于 2019-12-06 14:05:51

Arrays.asList() creates a fixed-size List that is directly backed by the varargs array parameter. Javadoc even says so:

Returns a fixed-size list backed by the specified array.

Its implementation of toArray() is a simple System.arraycopy(). Very fast.

On the other hand, when you do myList.stream().toArray(String[]::new), the size is not known, so the Stream.toArray() method has to consume the stream, collect all the values, then create the array and copy the values into the array. That is a lot slower, and requires a lot more memory.

In short, it's a waste of resources.

If you want simpler, just don't give the array size. It is still way faster and less memory intensive than using Streams:

String[] myArray1 = myList.toArray(new String[0]);

Under the hood, streams are much more complicated than plain arrays. Compilers will get better, but currently, sequential for loops should be faster than stream operations.

This article has some background about stream pipelines, which are used to implement streams. It can help to understand the complexity behind it.

The advantage of streams is that the code can be clearer and it is easier to parallelize it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!