Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stream.concat vs StreamEx
package com.soebes.performance.streams;
import org.openjdk.jmh.annotations.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import one.util.streamex.*;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Fork(3)
@State(Scope.Thread)
public class BenchmarkStreamConcat {
@Benchmark
public List<Element> with_new_arraylist(Container content) throws InterruptedException {
return content.getFancyStuffs().stream().flatMap(item -> {
ArrayList<Element> objects = new ArrayList<>();
objects.add(item.getElement());
objects.addAll(item.getElements());
return objects.stream();
}).collect(Collectors.toList());
}
@Benchmark
public List<Element> with_stream_concat(Container content) {
return content.getFancyStuffs()
.stream()
.flatMap(fs -> Stream.concat(Stream.of(fs.getElement()), fs.getElements().stream()))
.collect(Collectors.toList());
}
@Benchmark
public List<Element> with_streamex_complete(Container content) {
return StreamEx.of(content.getFancyStuffs())
.flatMap(fs -> StreamEx.of(fs.getElements()).prepend(fs.getElement()))
.toList();
}
@State(Scope.Thread)
public static class Container {
private List<FancyStuff> fancyStuffs;
public Container() {
this.fancyStuffs = Collections.emptyList();
}
@Param({"50", "100", "1000", "2000", "5000"})
int count;
@Setup(Level.Trial)
public void setup() {
fancyStuffs = IntStream.rangeClosed(1, count)
.mapToObj(i -> new FancyStuff(new Element(i + 1), createList(i)))
.collect(Collectors.toList());
}
@TearDown(Level.Trial)
public void tearDown() {
this.fancyStuffs = Collections.emptyList();
}
private List<Element> createList(int factor) {
return IntStream.rangeClosed(2, 50)
.mapToObj(i -> new Element(i * factor))
.collect(Collectors.toList());
}
public List<FancyStuff> getFancyStuffs() {
return fancyStuffs;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment