diff --git a/rules/S2864/java/rule.adoc b/rules/S2864/java/rule.adoc index 94ea5751d4d..1a48203a1fb 100644 --- a/rules/S2864/java/rule.adoc +++ b/rules/S2864/java/rule.adoc @@ -35,6 +35,63 @@ public void doSomethingWithMap(Map map) { } ---- +=== Benchmarks + +[options="header"] +|=== +| Method| size| Runtime| Average time| Error margin +| usingEntrySet| 10| Temurin 21| 27.48 ns/op| ±6.22 ns/op +| usingEntrySet| 1000| Temurin 21| 2480.26 ns/op| ±899.05 ns/op +| usingEntrySet| 10000| Temurin 21| 22745.78 ns/op| ±10505.46 ns/op +| usingKeySet| 10| Temurin 21| 49.70 ns/op| ±3.78 ns/op +| usingKeySet| 1000| Temurin 21| 5061.54 ns/op| ±2056.60 ns/op +| usingKeySet| 10000| Temurin 21| 46689.04 ns/op| ±14509.97 ns/op +|=== + +*Benchmarking code* + +The results were generated by running the following snippet with https://github.com/openjdk/jmh[JMH]. + +[source,java] +---- +@BenchmarkMode({Mode.AverageTime}) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@State(Scope.Benchmark) +public class S2864 { + @Param({"10", "1000", "10000"}) + int size; + + Map map; + + @Setup(Level.Trial) + public void setup() { + Random random = new Random(); + map = new HashMap<>(); + for (int i = 0; i < size; i++) { + map.put(i, random.nextInt()); + } + } + + @Benchmark + public int usingKeySet() { + int sumKeysValues = 0; + for (Integer key : map.keySet()) { + sumKeysValues += key + map.get(key); + } + return sumKeysValues; + } + + @Benchmark + public int usingEntrySet() { + int sumKeysValues = 0; + for (Map.Entry entry : map.entrySet()) { + sumKeysValues += entry.getKey() + entry.getValue(); + } + return sumKeysValues; + } +} +---- + == Resources === Documentation