Reduce allocations for empty ArgumentValue

Closes gh-1175

Signed-off-by: James Bodkin <james.bodkin@amphora.net>
[brian.clozel@broadcom.com: apply code conventions]
Signed-off-by: Brian Clozel <brian.clozel@broadcom.com>
This commit is contained in:
James Bodkin
2025-04-03 16:02:36 +01:00
committed by Brian Clozel
parent e2f954a2cf
commit eb5a83ab6a
2 changed files with 5 additions and 3 deletions

View File

@@ -49,6 +49,8 @@ import org.springframework.util.ObjectUtils;
*/
public final class ArgumentValue<T> {
private static final ArgumentValue<?> EMPTY = new ArgumentValue<>(null, false);
private static final ArgumentValue<?> OMITTED = new ArgumentValue<>(null, true);
@@ -118,7 +120,7 @@ public final class ArgumentValue<T> {
@Override
public boolean equals(Object other) {
// This covers OMITTED constant
// This covers EMPTY and OMITTED constant
if (this == other) {
return true;
}
@@ -142,8 +144,9 @@ public final class ArgumentValue<T> {
* @param <T> the type of value
* @param value the value to hold in the instance
*/
@SuppressWarnings("unchecked")
public static <T> ArgumentValue<T> ofNullable(@Nullable T value) {
return new ArgumentValue<>(value, false);
return (value != null) ? new ArgumentValue<>(value, false) : (ArgumentValue<T>) EMPTY;
}
/**

View File

@@ -74,7 +74,6 @@ class ArgumentValueTests {
}
@Test
void ifPresentShouldSkipWhenOmitted() {
AtomicBoolean called = new AtomicBoolean();
ArgumentValue.omitted().ifPresent(value -> called.set(true));