Created
November 23, 2025 20:09
-
-
Save jeffque/27f38e22effefd24e6f8b044b5e2707f to your computer and use it in GitHub Desktop.
Variante do https://gist.github.com/jeffque/423c4655b4ea82c4a2c8ced51595c2a6 , com filtro e mapeamento de valor
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
| package jeffque.bench; | |
| import org.openjdk.jmh.annotations.*; | |
| import org.openjdk.jmh.infra.Blackhole; | |
| import java.util.List; | |
| import java.util.Random; | |
| import java.util.concurrent.TimeUnit; | |
| import java.util.stream.IntStream; | |
| @Warmup(iterations = 2) | |
| @Measurement(iterations = 3, time = 2, timeUnit = TimeUnit.SECONDS) | |
| @Timeout(time = 500, timeUnit = TimeUnit.SECONDS) | |
| @BenchmarkMode(Mode.Throughput) | |
| public class SummationEvenSquares { | |
| @State(Scope.Benchmark) | |
| public static class Input { | |
| // @Param({ "10", "100", "1000", "100000", "10000000", "50000000" }) | |
| @Param({ "100000", "50000000" }) | |
| public int size; | |
| List<Integer> lista; | |
| @Setup(Level.Trial) | |
| public void criaEstado() { | |
| final var r = new Random(15); | |
| lista = IntStream.range(0, size) | |
| .mapToObj(id -> r.nextInt()) | |
| .toList(); | |
| } | |
| } | |
| @Benchmark | |
| public long withForIndex(Input i) { | |
| long result = 0; | |
| for (int idx = 0; idx < i.lista.size(); idx++) { | |
| final var l = i.lista.get(idx); | |
| if (l % 2 == 0) { | |
| result += l*l; | |
| } | |
| } | |
| return result; | |
| } | |
| @Benchmark | |
| public long withForeach(Input i) { | |
| long result = 0; | |
| for (int l: i.lista) { | |
| if (l % 2 == 0) { | |
| result += l*l; | |
| } | |
| } | |
| return result; | |
| } | |
| @Benchmark | |
| public long withStream(Input i) { | |
| return i.lista.stream().mapToInt(Integer::intValue).filter(l -> l % 2 == 0).map(l -> l*l).sum(); | |
| } | |
| @Benchmark | |
| public void noopForeach(Input i, Blackhole b) { | |
| for (int l: i.lista) { | |
| if (l % 2 == 0) { | |
| b.consume(l*l); | |
| } | |
| } | |
| } | |
| @Benchmark | |
| public int withForeachInt(Input i) { | |
| int result = 0; | |
| for (int l: i.lista) { | |
| if (l % 2 == 0) { | |
| result += l*l; | |
| } | |
| } | |
| return result; | |
| } | |
| @Benchmark | |
| public int withStreamAsWrapper(Input i) { | |
| return i.lista.stream().filter(l -> l % 2 == 0).map(l -> l*l).reduce(0, Integer::sum); | |
| } | |
| @Benchmark | |
| public int withStreamAsWrapperSquareInReduce(Input i) { | |
| return i.lista.stream().filter(l -> l % 2 == 0).reduce(0, (acc, l) -> acc + l*l); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Resultado: