Skip to content

Instantly share code, notes, and snippets.

@ifsantos
Created July 1, 2022 18:16
Show Gist options
  • Save ifsantos/c2deafd15c5b4f08dcaf6c41c20eb33a to your computer and use it in GitHub Desktop.
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
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