8238684: Override getOrDefault in immutable Map implementation

Reviewed-by: forax, psandoz, smarks
This commit is contained in:
Claes Redestad 2020-02-08 15:21:25 +01:00
parent 7552915d3f
commit ac69c7894d
2 changed files with 24 additions and 0 deletions

View File

@ -904,6 +904,20 @@ class ImmutableCollections {
@Override public V replace(K key, V value) { throw uoe(); }
@Override public boolean replace(K key, V oldValue, V newValue) { throw uoe(); }
@Override public void replaceAll(BiFunction<? super K,? super V,? extends V> f) { throw uoe(); }
/**
* @implNote {@code null} values are disallowed in these immutable maps,
* so we can improve upon the default implementation since a
* {@code null} return from {@code get(key)} always means the default
* value should be returned.
*/
@Override
public V getOrDefault(Object key, V defaultValue) {
V v;
return ((v = get(key)) != null)
? v
: defaultValue;
}
}
static final class Map1<K,V> extends AbstractImmutableMap<K,V> {

View File

@ -34,6 +34,9 @@ import java.util.concurrent.TimeUnit;
*/
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Fork(value = 3)
@Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 2, timeUnit = TimeUnit.SECONDS)
public class ImmutableColls {
public static String[] STRINGS = {"hi", "all", "of", "you"};
@ -217,6 +220,13 @@ public class ImmutableColls {
fm4.containsValue("hi");
}
@Benchmark
@CompilerControl(CompilerControl.Mode.DONT_INLINE)
public void getOrDefault(Blackhole bh) {
bh.consume(fm4.getOrDefault("hi", "test"));
bh.consume(fm4.getOrDefault("not_in_this_map", "test"));
}
public int sizeOf(List<String> list) {
return list.size();
}