Skip to content

Commit

Permalink
Avoid draining the ArrayPool with undisposed JsonDocuments (#2258)
Browse files Browse the repository at this point in the history
My understanding is this code is likely going to be overhauled to not use JsonDocument at all, but in the meantime we can make a small tweak to significantly improve throughput. JsonDocument.Parse creates a JsonDocument backed by one or more ArrayPool arrays; those arrays are returned when the instance is disposed.  If it's never disposed, the arrays are never returned to the pool. That means that creating but not disposing lots of JsonDocument instances ends up incurring the cost (and contention) of searching the ArrayPool but ends up falling back to allocating anyway.

The problem is that JsonClaimSet isn't disposable and so the underlying JsonDocument is never disposed. As a patch until the code is overhauled, we can use JsonElement.Clone(), which creates a new JsonDocument not backed by ArrayPool arrays... we can then dispose of the original in order to return the arrays to the pool.

This still isn't ideal, as we're doing more allocating and copying than we'd like, but it ends up being much better than without.

Co-authored-by: Stephen Toub <stoub@microsoft.com>
  • Loading branch information
jennyf19 and stephentoub committed Aug 25, 2023
1 parent af9abdb commit fc9da23
Showing 1 changed file with 4 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,16 @@ internal class JsonClaimSet

internal JsonClaimSet(JsonDocument jsonDocument)
{
RootElement = jsonDocument.RootElement;
RootElement = jsonDocument.RootElement.Clone();
jsonDocument.Dispose();
}

internal JsonClaimSet(byte[] jsonBytes)
internal JsonClaimSet(byte[] jsonBytes) : this(JsonDocument.Parse(jsonBytes))
{
RootElement = JsonDocument.Parse(jsonBytes).RootElement;
}

internal JsonClaimSet(string json)
internal JsonClaimSet(string json) : this(JsonDocument.Parse(json))
{
RootElement = JsonDocument.Parse(json).RootElement;
}

internal JsonElement RootElement { get; }
Expand Down

0 comments on commit fc9da23

Please sign in to comment.