Skip to content
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

update readMap to avoid resizing map during reading #84045

Merged
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions docs/changelog/84045.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
pr: 84045
summary: Update `readMap` to avoid resizing map during reading
area: Infra/Core
type: enhancement
issues: []
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,7 @@
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
Expand Down Expand Up @@ -607,11 +605,11 @@ public String[] readOptionalStringArray() throws IOException {
* If the returned map contains any entries it will be mutable. If it is empty it might be immutable.
*/
public <K, V> Map<K, V> readMap(Writeable.Reader<K> keyReader, Writeable.Reader<V> valueReader) throws IOException {
return readMap(keyReader, valueReader, HashMap::new);
return readMap(keyReader, valueReader, Maps::newHashMapWithExpectedSize);
}

public <K, V> Map<K, V> readOrderedMap(Writeable.Reader<K> keyReader, Writeable.Reader<V> valueReader) throws IOException {
return readMap(keyReader, valueReader, LinkedHashMap::new);
return readMap(keyReader, valueReader, Maps::newLinkedHashMapWithExpectedSize);
}

private <K, V> Map<K, V> readMap(Writeable.Reader<K> keyReader, Writeable.Reader<V> valueReader, IntFunction<Map<K, V>> constructor)
Expand Down
12 changes: 12 additions & 0 deletions server/src/main/java/org/elasticsearch/common/util/Maps.java
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,18 @@ private static Map<String, Object> flatten(List<Object> list, boolean ordered, S
* @return a new pre-sized {@link HashMap}
*/
public static <K, V> Map<K, V> newMapWithExpectedSize(int expectedSize) {
return newHashMapWithExpectedSize(expectedSize);
}

/**
* Returns a hash map with a capacity sufficient to keep expectedSize elements without being resized.
*
* @param expectedSize the expected amount of elements in the map
* @param <K> the key type
* @param <V> the value type
* @return a new pre-sized {@link HashMap}
*/
public static <K, V> Map<K, V> newHashMapWithExpectedSize(int expectedSize) {
return new HashMap<>(capacity(expectedSize));
}

Expand Down