.NET Core 3.0 introduced a json serializer in the System.Text.Json namespace to replace Newtonsoft.Json in high performance scenario. You’ll find many benchmark on other website showing the performance gains when switching to S.T.Json.

However, you can find some issue on GitHub that shows that the JsonSerializer is less performant or leads to memory leaks. This can be the case when not used as expected. In this post, I’ll show you why it is important to reuse the JsonSerializerOptions instance whenever it’s possible to avoid a performance penalty.

// The following code reuse the default options instance which is automatically cached
public void Serialize_DefaultOptions()
{
    for (var i = 0; i < 10_000; i++)
    {
        JsonSerializer.Serialize(_data);
    }
}

// The following code reuse the same options instance
public void Serialize_CachedOptions()
{
    var options = new JsonSerializerOptions { WriteIndented = false };
    for (var i = 0; i < 10_000; i++)
    {
        JsonSerializer.Serialize(_data, options);
    }
}

// ❌ Do not use the following code
// The following code doesn't reuse the options
public void Serialize_NewOptions()
{
    for (var i = 0; i < 10_000; i++)
    {
        JsonSerializer.Serialize(_data, new JsonSerializerOptions { WriteIndented = false });
    }
}

#.net #security

Avoid performance issue with JsonSerializer by reusing the same instance
3.35 GEEK