diff --git a/android/guava/src/com/google/common/collect/Maps.java b/android/guava/src/com/google/common/collect/Maps.java index 92261c4983a1..bf6b1cb8e385 100644 --- a/android/guava/src/com/google/common/collect/Maps.java +++ b/android/guava/src/com/google/common/collect/Maps.java @@ -56,6 +56,7 @@ import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; @@ -1290,7 +1291,12 @@ public static ImmutableMap toMap( @CanIgnoreReturnValue public static ImmutableMap uniqueIndex( Iterable values, Function keyFunction) { - if (values instanceof Collection) { + // We can provide a hint to the builder to preallocate the correct size when the iterable is + // either a List (which likely has a fast size() implementation), or an ImmutableCollection + // (which definitely has a fast size() implementation). While Collection also has a size() + // implementation, it _may_ require iteration over the entire collection (e.g., a + // FilteredCollection), which we want to avoid. + if (values instanceof List || values instanceof ImmutableCollection) { return uniqueIndex( values.iterator(), keyFunction, diff --git a/guava/src/com/google/common/collect/Maps.java b/guava/src/com/google/common/collect/Maps.java index 4c58fa66cd76..1f495281bfa3 100644 --- a/guava/src/com/google/common/collect/Maps.java +++ b/guava/src/com/google/common/collect/Maps.java @@ -56,6 +56,7 @@ import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; @@ -1324,7 +1325,12 @@ public static ImmutableMap toMap( @CanIgnoreReturnValue public static ImmutableMap uniqueIndex( Iterable values, Function keyFunction) { - if (values instanceof Collection) { + // We can provide a hint to the builder to preallocate the correct size when the iterable is + // either a List (which likely has a fast size() implementation), or an ImmutableCollection + // (which definitely has a fast size() implementation). While Collection also has a size() + // implementation, it _may_ require iteration over the entire collection (e.g., a + // FilteredCollection), which we want to avoid. + if (values instanceof List || values instanceof ImmutableCollection) { return uniqueIndex( values.iterator(), keyFunction,