Skip to content

Commit

Permalink
#14: cache JsonSerializerOptions
Browse files Browse the repository at this point in the history
  • Loading branch information
bmotmans committed Aug 9, 2023
1 parent 8c2adfe commit d159261
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions src/Vizor.ECharts/EChartBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 8,8 @@ namespace Vizor.ECharts;

public abstract class EChartBase : ComponentBase, IAsyncDisposable
{
// one instance per chart, we need it to pass state info of external data sources, ...
protected JsonSerializerOptions? jsonOpts;
private static JsonSerializerOptions? cachedJsonOpts;
protected JsonSerializerOptions? jsonOpts;

private readonly List<ExternalDataSourceConverter.FetchCommand> dataFetchCommands = new();
protected readonly string id = "chart" Guid.NewGuid().ToString().Replace("-", "");
Expand Down Expand Up @@ -41,6 41,13 @@ public abstract class EChartBase : ComponentBase, IAsyncDisposable
[Parameter]
public JsonConverter[]? JsonConverters { get; set; }

// see https://www.meziantou.net/avoid-performance-issue-with-jsonserializer-by-reusing-the-same-instance-of-json.htm
/// <summary>
/// Prefer to re-use the same JsonSerializerOptions
/// </summary>
[Parameter]
public bool CacheJsonSerializerOptions { get; set; } = true;

/// <summary>
/// Geo maps, see https://echarts.apache.org/en/api.html#echarts.registerMap
/// </summary>
Expand Down Expand Up @@ -90,9 97,27 @@ public async ValueTask DisposeAsync()
return (chartOpts, mapOpts, fetchOpts);
}

protected JsonSerializerOptions CreateSerializerOptions()
protected JsonSerializerOptions CreateSerializerOptions()
{
var jsonOpts = new JsonSerializerOptions()
// return cached instance if possible
if (CacheJsonSerializerOptions && cachedJsonOpts != null)
{
// double check that all custom JsonConverters are already added
if (JsonConverters != null)
{
foreach (var converter in JsonConverters)
{
if (!cachedJsonOpts.Converters.Contains(converter))
{
cachedJsonOpts.Converters.Add(converter);
}
}
}

return cachedJsonOpts;
}

var jsonOpts = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Expand All @@ -119,6 144,10 @@ protected JsonSerializerOptions CreateSerializerOptions()
jsonOpts.Converters.Add(new ExternalDataSourceConverter(dataFetchCommands, id));
jsonOpts.Converters.Add(new ExternalDataSourceRefConverter(dataFetchCommands, id));

// store the json opts for re-use later on
if (CacheJsonSerializerOptions && cachedJsonOpts == null)
cachedJsonOpts = jsonOpts;

return jsonOpts;
}
}

0 comments on commit d159261

Please sign in to comment.