Created
March 30, 2021 13:53
-
-
Save orionll/74128214ba1d2c1114cb2256a4b61343 to your computer and use it in GitHub Desktop.
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.Benchmark; | |
import org.openjdk.jmh.annotations.BenchmarkMode; | |
import org.openjdk.jmh.annotations.Mode; | |
import org.openjdk.jmh.annotations.OutputTimeUnit; | |
import org.openjdk.jmh.annotations.Param; | |
import org.openjdk.jmh.annotations.Scope; | |
import org.openjdk.jmh.annotations.Setup; | |
import org.openjdk.jmh.annotations.State; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.TimeUnit; | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
@BenchmarkMode(Mode.AverageTime) | |
@OutputTimeUnit(TimeUnit.NANOSECONDS) | |
@State(Scope.Thread) | |
public class ToListFilter { | |
@Param({"10", "1000"}) | |
private int size; | |
private List<Integer> sourceList; | |
@Setup | |
public void setup() { | |
sourceList = IntStream | |
.range(0, size) | |
.boxed() | |
.collect(Collectors.toList()); | |
} | |
@Benchmark | |
public List<Integer> collectToList() { | |
return sourceList.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()); | |
} | |
@Benchmark | |
public List<Integer> collectToUnmodifiableList() { | |
return sourceList.stream().filter(i -> i % 2 == 0).collect(Collectors.toUnmodifiableList()); | |
} | |
@Benchmark | |
public List<Integer> toList() { | |
return sourceList.stream().filter(i -> i % 2 == 0).toList(); | |
} | |
@Benchmark | |
public List<Integer> newArrayList() { | |
var list = new ArrayList<Integer>(); | |
for (var i : sourceList) { | |
if (i % 2 == 0) { | |
list.add(i); | |
} | |
} | |
return list; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment