Why overload the varargs () method in the Java Stream interface?

The Stream interface has two overloads for the of() method. One is the arity variable method, while the other takes one argument.

Is a one argument method optimizing performance compared to passing a single argument to an arity variable method? If so, how does this increase productivity? The same questions can be asked from the empty() method, which would seem to be syntactic sugar around the arity of() variable.

I see that the implementation is different between these methods, with the difference apparently in how the Spliterator is created; but what advantage does the Stream API offer?

+5
source share
3 answers

Yes, this is an optimization to avoid the overhead of creating an array to hold only one item that you will get if you use the varargs version.

The same questions can be asked from the empty () method, which will appear to be syntactic sugar around the arity () variable

What version of implementation are you viewing? When I look at the implementation, I do not see this.

+5
source

An empty stream and a stream of individual elements are very common use cases, especially if you use .flatMap() . For example, here Optional.stream() implemented in Java-9:

 public Stream<T> stream() { if (!isPresent()) { return Stream.empty(); } else { return Stream.of(value); } } 

Therefore, given the options stream, you can expand them into a flat stream as follows:

 streamOfOptionals.flatMap(Optional::stream); 

Here you create a lot of empty threads, as well as threads of individual elements, so the optimization of such cases looks very reasonable. In particular, Stream.empty() , unlike Stream.of() does not create an empty array and does not create a spliterator (it reuses the same instance of spliterator). Stream.of(T) also especially optimized inside StreamBuilderImpl , therefore an array is not allocated for one element.

+5
source

I came across an official resource that confirms previous answers to this question: JEP 269: Convenience Factory Collection Methods . The description of this proposal is to

Provide static Factory methods on the List , Set and Map interfaces to create non-modifiable instances of these collections.

They will include varargs overloads, so there will be no fixed limit on the size of the collection ... Special APIs (overload with fixed argument) for up to ten elements will be provided. Although this introduces some confusion into the API, it avoids the overhead of array allocation, initialization, and garbage collection resulting from varargs calls.

Thus, performance optimization is just to avoid the array of varargs method.

+1
source

Source: https://habr.com/ru/post/1244446/


All Articles