Refactor JsonWorkflowStateSerializer to improve performance

- **Improves performance:** The converters and static properties are pre-configured when the class is initialized. Only the `ReferenceHandler` is refreshed per call, avoiding repeated configuration of common options like converters.
- **Thread-safe:** Since `_cachedOptions` is immutable, it can safely be reused across threads.

**Tradeoffs:** Small performance cost during cloning, but still much faster than fully recreating options each time.
This commit is contained in:
Sipke Schoorstra 2025-01-06 15:34:43 +01:00
parent 965a67c62f
commit ba4645ea62

View file

@ -129,29 +129,18 @@ public class JsonWorkflowStateSerializer : ConfigurableSerializer, IWorkflowStat
/// <inheritdoc />
public override JsonSerializerOptions GetOptions()
{
// Bypass cached options to ensure that the reference handler is always fresh.
return GetOptionsInternal();
}
/// <inheritdoc />
protected override void Configure(JsonSerializerOptions options)
{
var referenceHandler = new CrossScopedReferenceHandler();
options.ReferenceHandler = referenceHandler;
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.PropertyNameCaseInsensitive = true;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
var options = base.GetOptions();
return new JsonSerializerOptions(options)
{
ReferenceHandler = new CrossScopedReferenceHandler()
};
}
/// <inheritdoc />
protected override void AddConverters(JsonSerializerOptions options)
{
options.Converters.Add(new JsonStringEnumConverter());
options.Converters.Add(new TypeJsonConverter(_wellKnownTypeRegistry));
options.Converters.Add(JsonMetadataServices.TimeSpanConverter);
options.Converters.Add(new PolymorphicObjectConverterFactory(_wellKnownTypeRegistry));
options.Converters.Add(new TypeJsonConverter(_wellKnownTypeRegistry));
options.Converters.Add(new VariableConverterFactory(_wellKnownTypeRegistry, _loggerFactory));
}
}