BoundField.write memory optimization (#2325)

* BoundField.write memory optimization

Declare and initialize the type adapter used for writing BoundFields outside of the anonymous class to ensure that a new TypeAdapterRuntimeTypeWrapper is not constructed each time a BoundField is written. This type adapter is only initialized if the BoundField will be used for serialization.

* Avoid confusing nullness-analysis tools
This commit is contained in:
sembseth 2023-02-28 23:46:05 +01:00 committed by GitHub
parent 9f46977d57
commit 105f28ffe6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 9 additions and 3 deletions

View File

@ -161,6 +161,14 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
final TypeAdapter<Object> typeAdapter = (TypeAdapter<Object>) mapped;
final TypeAdapter<Object> writeTypeAdapter;
if (serialize) {
writeTypeAdapter = jsonAdapterPresent ? typeAdapter
: new TypeAdapterRuntimeTypeWrapper<>(context, typeAdapter, fieldType.getType());
} else {
// Will never actually be used, but we set it to avoid confusing nullness-analysis tools
writeTypeAdapter = typeAdapter;
}
return new BoundField(name, field, serialize, deserialize) {
@Override void write(JsonWriter writer, Object source)
throws IOException, IllegalAccessException {
@ -191,9 +199,7 @@ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory {
return;
}
writer.name(name);
TypeAdapter<Object> t = jsonAdapterPresent ? typeAdapter
: new TypeAdapterRuntimeTypeWrapper<>(context, typeAdapter, fieldType.getType());
t.write(writer, fieldValue);
writeTypeAdapter.write(writer, fieldValue);
}
@Override