Skip to content

Commit afcefdd

Browse files
authored
[7.x] Optimize allocations for List.copyOf and Set.copyOf (#79395)
We can optimize away the array allocation just to call `List.of/Set.of` and instead create copies directly based the supplied collection.
1 parent d8c1428 commit afcefdd

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

libs/core/src/main/java/org/elasticsearch/core/List.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
package org.elasticsearch.core;
1010

11+
import java.util.ArrayList;
1112
import java.util.Arrays;
1213
import java.util.Collection;
1314
import java.util.Collections;
@@ -75,8 +76,14 @@ public static <T> java.util.List<T> of(T... entries) {
7576
* @param coll a {@code Collection} from which elements are drawn, must be non-null
7677
* @return a {@code List} containing the elements of the given {@code Collection}
7778
*/
78-
@SuppressWarnings("unchecked")
7979
public static <T> java.util.List<T> copyOf(Collection<? extends T> coll) {
80-
return (java.util.List<T>) List.of(coll.toArray());
80+
switch (coll.size()) {
81+
case 0:
82+
return Collections.emptyList();
83+
case 1:
84+
return Collections.singletonList(coll.iterator().next());
85+
default:
86+
return Collections.unmodifiableList(new ArrayList<>(coll));
87+
}
8188
}
8289
}

libs/core/src/main/java/org/elasticsearch/core/Set.java

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,9 @@ public static <T> java.util.Set<T> of(T e1, T e2) {
6161
public static <T> java.util.Set<T> of(T... entries) {
6262
switch (entries.length) {
6363
case 0:
64-
return Set.of();
64+
return of();
6565
case 1:
66-
return Set.of(entries[0]);
66+
return of(entries[0]);
6767
default:
6868
return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(entries)));
6969
}
@@ -78,8 +78,14 @@ public static <T> java.util.Set<T> of(T... entries) {
7878
* @throws NullPointerException if coll is null, or if it contains any nulls
7979
* @since 10
8080
*/
81-
@SuppressWarnings("unchecked")
8281
public static <T> java.util.Set<T> copyOf(Collection<? extends T> coll) {
83-
return (java.util.Set<T>) Set.of(new HashSet<>(coll).toArray());
82+
switch (coll.size()) {
83+
case 0:
84+
return Collections.emptySet();
85+
case 1:
86+
return Collections.singleton(coll.iterator().next());
87+
default:
88+
return Collections.unmodifiableSet(new HashSet<>(coll));
89+
}
8490
}
8591
}

0 commit comments

Comments
 (0)