Custom spliterator for Collections.nCopies(n, obj).stream()

Tagir F. Valeev amaembo at
Tue Jul 28 08:37:38 UTC 2015


Current implementation of Collections.nCopies().stream() is as

public Stream<E> stream() {
    return IntStream.range(0, n).mapToObj(i -> element);

public Stream<E> parallelStream() {
    return IntStream.range(0, n).parallel().mapToObj(i -> element);

The problem is that it adds a lambda expression to the
RangeIntSpliterator type profile which can be polluted by some other
code and vice versa: using nCopies().stream() may pollute the type
profile for other code making it slower.

Another thing which is missing in current implementation is unordered
mode. This collection is unordered by nature, its stream is similar to
Stream.generate(), so to my opinion it should be unordered which may
improve the parallel reduction in some cases.

This can be improved by introducing the custom spliterator class which
is quite simple:

On pre-polluted type profile with simple mapping and reduction using
custom spliterator is about 25-30% faster in both parallel and
sequential cases as benchmarking shows (performed on 4-core cpu).

What do you think?

With best regards,
Tagir Valeev.

More information about the core-libs-dev mailing list