Class PooledArrayConverter<T>
- Namespace
- MassiveDotNet.Serialization
- Assembly
- MassiveDotNet.dll
Reads a JSON array into a pooled buffer and copies it out once, so materializing a large result page allocates the array it returns and nothing else.
public sealed class PooledArrayConverter<T> : JsonConverter<T[]>
Type Parameters
TThe element type, resolved through the serializer's source-generated context.
- Inheritance
-
JsonConverter<T[]>PooledArrayConverter<T>
- Inherited Members
Remarks
System.Text.Json builds an array by filling a List<T> and calling
ToArray. List<T> doubles its backing array as it grows, so every
intermediate buffer is discarded. For a class element each discarded slot is an 8-byte
reference and the churn disappears against the objects themselves; for an 88-byte
readonly record struct row (decision D4) each slot is the whole value, and a
50,000-row response allocated 8.8 times the array it returned.
Renting the growth buffers instead means they are reused rather than collected, which leaves
the returned array as very nearly the only allocation on the path. The buffer is returned in a
finally so a malformed body cannot leak it out of the pool, and cleared on return only
when T carries references, since clearing a block of numeric structs
costs a memset for no benefit.
Applied by the generator as a property attribute rather than registered as a
JsonConverterFactory: a factory has to build its converter through
MakeGenericType, which is reflection over a generic instantiation the trimmer cannot
see, and constitution rules 3 and 4 rule that out. An attribute names the closed type at
compile time, so every instantiation is rooted in the generated code.
Methods
Read(ref Utf8JsonReader, Type, JsonSerializerOptions)
Reads and converts the JSON to type T.
public override T[]? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
Parameters
readerUtf8JsonReaderThe reader.
typeToConvertTypeThe type to convert.
optionsJsonSerializerOptionsAn object that specifies serialization options to use.
Returns
- T[]
The converted value.
Write(Utf8JsonWriter, T[], JsonSerializerOptions)
Writes a specified value as JSON.
public override void Write(Utf8JsonWriter writer, T[] value, JsonSerializerOptions options)
Parameters
writerUtf8JsonWriterThe writer to write to.
valueT[]The value to convert to JSON.
optionsJsonSerializerOptionsAn object that specifies serialization options to use.