Skip to content

Modify rule S2864: add benchmark results #5079

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 30, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions rules/S2864/java/rule.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,63 @@ public void doSomethingWithMap(Map<String,Object> 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<Integer,Integer> 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<Integer, Integer> entry : map.entrySet()) {
sumKeysValues += entry.getKey() + entry.getValue();
}
return sumKeysValues;
}
}
----

== Resources

=== Documentation
Expand Down