Skip to content

Commit 8021727

Browse files
authored
api: Size Sets and Maps correctly in handling of Metadata values to be exchanged during a call (#12229)
Fix HashSet / HashMap initializations to have sufficient capacity allocated based on the number of keys to be inserted, without which it would always lead to a rehash / resize operation.
1 parent 2e96fbf commit 8021727

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

api/src/main/java/io/grpc/Metadata.java

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222

2323
import com.google.common.annotations.VisibleForTesting;
2424
import com.google.common.base.Preconditions;
25+
import com.google.common.collect.Maps;
26+
import com.google.common.collect.Sets;
2527
import com.google.common.io.BaseEncoding;
2628
import com.google.common.io.ByteStreams;
2729
import java.io.ByteArrayInputStream;
@@ -32,8 +34,6 @@
3234
import java.util.Arrays;
3335
import java.util.BitSet;
3436
import java.util.Collections;
35-
import java.util.HashMap;
36-
import java.util.HashSet;
3737
import java.util.Iterator;
3838
import java.util.List;
3939
import java.util.Locale;
@@ -325,7 +325,7 @@ public Set<String> keys() {
325325
if (isEmpty()) {
326326
return Collections.emptySet();
327327
}
328-
Set<String> ks = new HashSet<>(size);
328+
Set<String> ks = Sets.newHashSetWithExpectedSize(size);
329329
for (int i = 0; i < size; i++) {
330330
ks.add(new String(name(i), 0 /* hibyte */));
331331
}
@@ -526,7 +526,7 @@ public void merge(Metadata other) {
526526
public void merge(Metadata other, Set<Key<?>> keys) {
527527
Preconditions.checkNotNull(other, "other");
528528
// Use ByteBuffer for equals and hashCode.
529-
Map<ByteBuffer, Key<?>> asciiKeys = new HashMap<>(keys.size());
529+
Map<ByteBuffer, Key<?>> asciiKeys = Maps.newHashMapWithExpectedSize(keys.size());
530530
for (Key<?> key : keys) {
531531
asciiKeys.put(ByteBuffer.wrap(key.asciiName()), key);
532532
}

0 commit comments

Comments
 (0)