Hello!

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

http://hg.openjdk.java.net/jdk9/dev/jdk/file/f160dec9a350/src/java.base/share/classes/java/util/Collections.java#l5066

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

@Override
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:
https://gist.github.com/amaembo/62f3efee9923b1468e86

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.

Reply via email to