Skip to content

Reduce allocations when reading json/jsonb with Npgsql.Json.NET - #6768

Open
gdoron wants to merge 3 commits into
npgsql:mainfrom
gdoron:jsonnet-fewer-allocations
Open

gdoron wants to merge 3 commits into
npgsql:mainfrom
gdoron:jsonnet-fewer-allocations

Conversation

@gdoron

@gdoron gdoron commented Nov 22, 2026

Copy link
Copy Markdown

Fixes #6767

Before this change, JsonNetJsonConverter did two wasteful things:

  • Every value it read was copied into a new MemoryStream, then deserialized through a new StreamReader and JsonTextReader.
  • Every value it read or wrote created a new JsonSerializer.

This PR changes three things:

  1. Reuse the serializer. The JsonSerializer is now created once per converter. Its settings are already captured when the resolver is constructed, so behavior is unchanged.
  2. Read without copying. When the value is already in the read buffer, it's decoded from there (TryReadBytes). Otherwise it's first read, sync or async, into an array rented from ArrayPool, as JsonConverter (System.Text.Json) already does. Json.NET still never does sync I/O (Fix reading columns asynchronously via JsonNet plugin #6109). Deserialization reads from a pooled char[] through a minimal TextReader, and JsonTextReader.ArrayPool is set so its own buffer is pooled too.
  3. New test. It reads a 100 KB value with SequentialAccess, both sync and async. This is the only path that falls back to the rented array; I checked that none of the existing tests reach it.

Benchmark results, against main on the same machine (benchmark code and full table are in #6767):

Allocated (main → PR)
Read POCO, 1,000 × ~370 B 7,588 KB → 1,612 KB (−79%)
Read POCO, 100 × ~24 KB 10,078 KB → 7,172 KB (−29%)
Read JObject, 1,000 × ~370 B 14,252 KB → 8,275 KB (−42%)

Mean time is unchanged within noise in this I/O-bound benchmark. Gen0 collections drop by about 5 times for small documents.

The JsonNet and Json tests pass for both json and jsonb fixtures (72 tests, on .NET 11 with PostgreSQL 17).

@gdoron
gdoron marked this pull request as ready for review November 22, 2026 11:48
@gdoron
gdoron requested review from roji and vonzshik as code owners November 22, 2026 11:48

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Npgsql.Json.NET allocates a MemoryStream, StreamReader and JsonSerializer for every json/jsonb value it reads

1 participant