Avoid draining the ArrayPool with undisposed JsonDocuments #2178
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.