Skip to content

Instantly share code, notes, and snippets.

@gunnarmorling
Created January 20, 2021 14:13
Show Gist options
  • Save gunnarmorling/dfac1964ad0f9a76619d5f70e73189b0 to your computer and use it in GitHub Desktop.
Save gunnarmorling/dfac1964ad0f9a76619d5f70e73189b0 to your computer and use it in GitHub Desktop.
/*
* Copyright Gunnar Morling.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package dev.morling;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
public class CollectToListBenchmark {
@State(Scope.Thread)
public static class MyState {
Random random = ThreadLocalRandom.current();
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void sequentialCollector(MyState state, Blackhole blackhole) {
List<Long> longs = state.random.ints(100000)
.map(Math::abs)
.mapToObj(Long::valueOf)
.map(i -> i * 2)
.collect(Collectors.toList());
blackhole.consume(longs);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void sequentialToList(MyState state, Blackhole blackhole) {
List<Long> longs = state.random.ints(100000)
.map(Math::abs)
.mapToObj(Long::valueOf)
.map(i -> i * 2)
.toList();
blackhole.consume(longs);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void parallelCollector(MyState state, Blackhole blackhole) {
List<Long> longs = state.random.ints(100000)
.parallel()
.map(Math::abs)
.mapToObj(Long::valueOf)
.map(i -> i * 2)
.collect(Collectors.toList());
blackhole.consume(longs);
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
public void parallelToList(MyState state, Blackhole blackhole) {
List<Long> longs = state.random.ints(100000)
.parallel()
.map(Math::abs)
.mapToObj(Long::valueOf)
.map(i -> i * 2)
.toList();
blackhole.consume(longs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment