Created
July 1, 2022 18:16
-
-
Save ifsantos/c2deafd15c5b4f08dcaf6c41c20eb33a to your computer and use it in GitHub Desktop.
Measure the performance between "foreach adding items" and "map collecting items" using jmh . Further possibilites include mapWithParallelStream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.openjdk.jmh.annotations.*; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.Objects; | |
import java.util.Random; | |
import static java.util.stream.Collectors.joining; | |
import static java.util.stream.Collectors.toList; | |
@State(Scope.Thread) | |
@BenchmarkMode(Mode.AverageTime) | |
public class MicroBenchmarks { | |
private int n = 1000000; | |
private final List<String> csv = new ArrayList<>(); | |
@Setup public void initList() { | |
Random r = new Random(); | |
for (int i = 0; i < n; i++) { | |
String line = r.ints(5) | |
.mapToObj(String::valueOf) | |
.collect(joining(",")); | |
csv.add(i % 5 == 0 ? null : line); | |
} | |
} | |
@Benchmark public List<String> forEach() { | |
List<String> result = new ArrayList<> (); | |
csv.stream() | |
.filter(e -> e != null) | |
.forEach(s -> result.add(parse(s))); | |
return result; | |
} | |
@Benchmark public List<String> map() { | |
return csv.stream() | |
.filter(Objects::nonNull) | |
.map(this::parse) | |
.collect(toList()); | |
} | |
private String parse(String line) { | |
return line.split(",")[0]; | |
} | |
} | |
/* | |
For further information check | |
https://bitbucket.org/assylias/performance/ | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment