Improve immutable wrapped array list performance

This commit is contained in:
Andrea Cavalli 2023-11-29 15:49:09 +01:00
parent 87f31652d7
commit 4654b690fe
3 changed files with 18 additions and 5 deletions

View File

@ -125,9 +125,9 @@ public class GenSerializerArrayX extends ClassGenerator {
method.addCode("\n");
if (USE_NATIVE_TYPED_ARRAYS) {
method.addStatement("return new $T(a)", ParameterizedTypeName.get(ClassName.get(ImmutableWrappedArrayList.class), arrayComponentTypeName));
method.addStatement("return $T.of(a)", ParameterizedTypeName.get(ClassName.get(ImmutableWrappedArrayList.class), arrayComponentTypeName));
} else {
method.addStatement("return ($T) new $T(a)",
method.addStatement("return ($T) $T.of(a)",
ParameterizedTypeName.get(ClassName.get(ImmutableWrappedArrayList.class), arrayComponentTypeName),
ClassName.get(ImmutableWrappedArrayList.class)
);

View File

@ -32,6 +32,8 @@ import java.util.function.Consumer;
import org.jetbrains.annotations.NotNull;
public class ImmutableWrappedArrayList<K> extends AbstractObjectList<K> implements RandomAccess {
private static final ImmutableWrappedArrayList<?> EMPTY = new ImmutableWrappedArrayList<>(new Object[0]);
/** The backing array. */
protected final K[] a;
/** The current actual size of the list (never greater than the backing-array length). */
@ -42,7 +44,7 @@ public class ImmutableWrappedArrayList<K> extends AbstractObjectList<K> implemen
*
* @param a an array whose elements will be used to fill the array list.
*/
public ImmutableWrappedArrayList(final K[] a) {
private ImmutableWrappedArrayList(final K[] a) {
this.a = a;
this.size = a.length;
}
@ -55,7 +57,18 @@ public class ImmutableWrappedArrayList<K> extends AbstractObjectList<K> implemen
*/
@SafeVarargs
public static <K> ImmutableWrappedArrayList<K> of(final K... init) {
return new ImmutableWrappedArrayList<>(init);
return init.length == 0 ? of() : new ImmutableWrappedArrayList<>(init);
}
/**
* Creates an array list using an array of elements.
*
* @param init a the array the will become the new backing array of the array list.
* @return a new array list backed by the given array.
*/
public static <K> ImmutableWrappedArrayList<K> of() {
//noinspection unchecked
return (ImmutableWrappedArrayList<K>) EMPTY;
}
private UnsupportedOperationException ex() {

View File

@ -16,7 +16,7 @@ public class UpgradeUtil {
for (int i = 0; i < array.length; i++) {
array[i] = (B) upgrader.upgrade((A) array[i]);
}
return (ImmutableWrappedArrayList<B>) new ImmutableWrappedArrayList<>(array);
return (ImmutableWrappedArrayList<B>) ImmutableWrappedArrayList.of(array);
}
public static <A, B> B upgradeNullable(A nullableValue, DataUpgrader<A, B> upgrader) {