Java8 parallelStream performance test

  jmh

Order

This paper mainly studies the performance of parallelStream.

Test 1

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 3, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 20, time = 3, timeUnit = TimeUnit.SECONDS)
@Fork(1)
@State(Scope.Benchmark)
public class StreamBenchTest {
    List<String> data = new ArrayList<>();

    @Setup
    public void init() {
        // prepare
        for(int i=0;i<100;i++){
            data.add(UUID.randomUUID().toString());
        }
    }

    @TearDown
    public void destory() {
        // destory
    }

    @Benchmark
    public void benchStream(){
        data.stream().forEach(e -> {
            e.getBytes();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        });
    }

    @Benchmark
    public void benchParallelStream(){
        data.parallelStream().forEach(e -> {
            e.getBytes();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        });
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(".*" +StreamBenchTest.class.getSimpleName()+ ".*")
                .forks(1)
                .build();
        new Runner(opt).run();
    }

}

ParallelStream threads

The default is runtime. getruntime (). availableprocessors ()-1, here is 7

Running results

# Run complete. Total time: 00:02:44

Benchmark                            Mode  Cnt           Score         Error  Units
StreamBenchTest.benchParallelStream  avgt   20   155868805.437 ± 1509175.840  ns/op
StreamBenchTest.benchStream          avgt   20  1147570372.950 ± 6138494.414  ns/op

Test 2

Change data to 30 and sleep to 100

Benchmark                            Mode  Cnt           Score         Error  Units
StreamBenchTest.benchParallelStream  avgt   20   414230854.631 ±  725294.455  ns/op
StreamBenchTest.benchStream          avgt   20  3107250608.500 ± 4805037.628  ns/op

It can be found that the longer the sleep, the more obvious the advantage of parallelStream.

Summary

ParallelStream has more obvious advantages in blocking scenarios, and the number of thread pools defaults to
Runtime.getruntime (). availableprocessors ()-1, set if necessary-djava.util.concurrent.forkjoinpool.common.parallelism = 8

doc