Skip to content

Commit

Permalink
[7.x] Optimize allocations for List.copyOf and Set.copyOf (#79395)
Browse files Browse the repository at this point in the history
We can optimize away the array allocation just
to call `List.of/Set.of` and instead create copies directly
based the supplied collection.
  • Loading branch information
arteam authored Oct 19, 2021
1 parent d8c1428 commit afcefdd
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
11 changes: 9 additions & 2 deletions libs/core/src/main/java/org/elasticsearch/core/List.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

package org.elasticsearch.core;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
Expand Down Expand Up @@ -75,8 +76,14 @@ public static <T> java.util.List<T> of(T... entries) {
* @param coll a {@code Collection} from which elements are drawn, must be non-null
* @return a {@code List} containing the elements of the given {@code Collection}
*/
@SuppressWarnings("unchecked")
public static <T> java.util.List<T> copyOf(Collection<? extends T> coll) {
return (java.util.List<T>) List.of(coll.toArray());
switch (coll.size()) {
case 0:
return Collections.emptyList();
case 1:
return Collections.singletonList(coll.iterator().next());
default:
return Collections.unmodifiableList(new ArrayList<>(coll));
}
}
}
14 changes: 10 additions & 4 deletions libs/core/src/main/java/org/elasticsearch/core/Set.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ public static <T> java.util.Set<T> of(T e1, T e2) {
public static <T> java.util.Set<T> of(T... entries) {
switch (entries.length) {
case 0:
return Set.of();
return of();
case 1:
return Set.of(entries[0]);
return of(entries[0]);
default:
return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(entries)));
}
Expand All @@ -78,8 +78,14 @@ public static <T> java.util.Set<T> of(T... entries) {
* @throws NullPointerException if coll is null, or if it contains any nulls
* @since 10
*/
@SuppressWarnings("unchecked")
public static <T> java.util.Set<T> copyOf(Collection<? extends T> coll) {
return (java.util.Set<T>) Set.of(new HashSet<>(coll).toArray());
switch (coll.size()) {
case 0:
return Collections.emptySet();
case 1:
return Collections.singleton(coll.iterator().next());
default:
return Collections.unmodifiableSet(new HashSet<>(coll));
}
}
}

0 comments on commit afcefdd

Please sign in to comment.