Last active
November 23, 2025 18:47
-
-
Save jeffque/423c4655b4ea82c4a2c8ced51595c2a6 to your computer and use it in GitHub Desktop.
Benchmark de soma de iteração de arraylist vs stream
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 Summation { | |
| @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++) { | |
| result += i.lista.get(idx); | |
| } | |
| return result; | |
| } | |
| @Benchmark | |
| public long withForeach(Input i) { | |
| long result = 0; | |
| for (int l: i.lista) { | |
| result += l; | |
| } | |
| return result; | |
| } | |
| @Benchmark | |
| public long withStream(Input i) { | |
| return i.lista.stream().mapToInt(Integer::intValue).sum(); | |
| } | |
| @Benchmark | |
| public void noopForeach(Input i, Blackhole b) { | |
| for (int l: i.lista) { | |
| b.consume(l); | |
| } | |
| } | |
| @Benchmark | |
| public int withForeachInt(Input i) { | |
| int result = 0; | |
| for (int l: i.lista) { | |
| result += l; | |
| } | |
| return result; | |
| } | |
| // baseado em https://www.baeldung.com/java-streams-vs-loops | |
| @Benchmark | |
| public int withStreamAsWrapper(Input i) { | |
| return i.lista.stream().reduce(0, Integer::sum); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Resultados que obtive localmente após adicionar a função
withStreamAsWrapper(para simular o resultado de https://www.baeldung.com/java-streams-vs-loops) e usandointemwithForeachIntcomo tipo acumulador:Dados sobre ambiente de test:
JMH version: 1.37
VM version: JDK 21.0.3, OpenJDK 64-Bit Server VM, 21.0.3+9-LTS
Rodado em um MacBook Pro, macOs 15.6.1, 15 GB de RAM, processador Apple M1 Pro