I have written a benchmark for get
and remove
of HashMap
as below:
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class HashMapBenchmark {
@State(Scope.Benchmark)
public static class Mystate {
HashMap<String,String> hashmapVar = new HashMap<String,String>();
String key0 = "bye";
@Setup(Level.Iteration)
public void setup(){
hashmapVar.put(key0,"bubye");
}
}
@Benchmark
public void hashmapGet(Mystate state ,Blackhole bh) {
bh.consume(state.hashmapVar.get(state.key0));
}
@Benchmark
public void hashmapRemove(Mystate state ,Blackhole bh) {
bh.consume(state.hashmapVar.remove(state.key0));
}
}
It produces this result:
Benchmark Mode Samples Score Score error Units
c.b.HashMapBenchmark.hashmapGet avgt 60 6.348 0.320 ns/op
c.b.HashMapBenchmark.hashmapRemove avgt 60 5.180 0.074 ns/op
As per the result, remove()
is slight faster than get()
.
Even to remove an element, first it has to retrieve the element, doesn't it?
How can remove()
be faster? Or am I missing something?
Update After using the latest JMH (1.11.3) and here is the result:
Benchmark Mode Cnt Score Error Units
HashMapBenchmark.hashmapGet avgt 60 9.713 ± 0.277 ns/op
HashMapBenchmark.hashmapRemove avgt 60 7.677 ± 0.166 ns/op
mvn archetype:generate -DinteractiveMode=false -DarchetypeGroupId=org.openjdk.jmh -DarchetypeArtifactId=jmh-java-benchmark-archetype
– Politicaljmh-core
) And if I remember correctly, it's a propertyjmh.version
defined in the<properties>
section. – Cholla<jmh.version>1.0</jmh.version>
– Politicalget
gets de-optimised after a few iterations. – Aurakey0
andhashMapVar
public and final, and suddenly the difference is much smaller. – Wail