Repository navigation
Open
Description
The issue
JsonNetJsonConverter does this for every json/jsonb value it reads (source):
using var stream = reader.GetStream();
var mem = new MemoryStream();
// copy the whole value into mem
var jsonSerializer = JsonSerializer.CreateDefault(settings);
using var textReader = new JsonTextReader(new StreamReader(mem, encoding));
return jsonSerializer.Deserialize(textReader, type);So each value allocates:
- a
MemoryStreamand its growing buffer - a
StreamReader, with its byte and char buffers - a
JsonTextReaderchar buffer - a new
JsonSerializer
BindValue also creates a new JsonSerializer for every value it writes.
Two things are worth noting:
- The copy is there so that Json.NET, which only reads synchronously, never does sync I/O (Fix reading columns asynchronously via JsonNet plugin #6109). But when the value is already in the read buffer, which is always true without
SequentialAccess, nothing needs copying:GetStream()already returns a view over the buffer. - The resolvers already capture the settings when they're constructed (
// Capture default settings during construction.), so creating the serializer once per converter keeps the behavior the same.
The same code is in 10.0.x, 11.0.0 and main.
Measurements
These are BenchmarkDotNet results. The benchmark reads a jsonb column with UseJsonNet() (code below) and was run against main and against the proposed change. There are two payload sizes:
- Small: 1,000 rows of about 370 B.
- Large: 100 rows of about 24 KB, larger than the 8 KB read buffer.
| Method | Size | Allocated (main) | Allocated (fix) | Δ | Gen0/op (main → fix) |
|---|---|---|---|---|---|
| ReadPocoAsync | Small | 7,588 KB | 1,612 KB | −79% | 906 → 188 |
| ReadPocoSync | Small | 7,517 KB | 1,541 KB | −80% | 918 → 188 |
| ReadJObjectAsync | Small | 14,252 KB | 8,275 KB | −42% | 1,742 → 1,008 |
| ReadPocoAsync | Large | 10,078 KB | 7,172 KB | −29% | 1,234 → 875 |
| ReadPocoSync | Large | 10,072 KB | 7,165 KB | −29% | 1,219 → 875 |
| ReadJObjectAsync | Large | 62,441 KB | 59,534 KB | −5% | 7,625 → 7,281 |
| WritePocoAsync (100 params) | Small | 421 KB | 399 KB | −5% | 51 → 49 |
- About 6 KB is allocated per value on top of the deserialized object. For a 370 B document that is roughly 16 times the document's size.
- Almost all of the saving comes from no longer copying each value into a
MemoryStreamand wrapping it in aStreamReader. - Reusing the serializer saves about 220 B per value, on both reads and writes.
- Mean time didn't change beyond noise in this benchmark: for example, ReadPocoSync Small went from 2.97 ms to 2.98 ms, and Large from 10.93 ms to 10.67 ms. Against a local server, time is dominated by I/O. The gain is fewer gen0 GCs (about 5 times fewer for small documents), which matters under load.
Environment:
- Npgsql main (c687896), Newtonsoft.Json 13.0.4
- PostgreSQL 17.11 (Docker)
- .NET 11.0.0, macOS arm64 (Apple M5 Pro)
- BenchmarkDotNet 0.15.8, run in-process because 0.15.8 can't build a separate net11.0 process
Proposed fix
I'll open a PR that does the following:
- Creates the
JsonSerializeronce per converter. - When the value is in the read buffer, decodes it straight from there (
TryReadBytes). Otherwise it first reads it, sync or async, into an array rented fromArrayPool, as the System.Text.Json converter already does. It then deserializes from a pooledchar[]through a minimalTextReader, withJsonTextReader.ArrayPoolset.
Benchmark code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Toolchains.InProcess.Emit;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Npgsql.Benchmarks;
[MemoryDiagnoser]
[Config(typeof(InProcessConfig))]
public class JsonNetRead
{
// BenchmarkDotNet 0.15.8 can't build a separate net11.0 process, so the job runs in-process.
sealed class InProcessConfig : ManualConfig
{
public InProcessConfig()
=> AddJob(Job.Default.WithWarmupCount(3).WithIterationCount(10).WithToolchain(InProcessEmitToolchain.Instance));
}
public enum PayloadSize { Small, Large }
[Params(PayloadSize.Small, PayloadSize.Large)]
public PayloadSize Size { get; set; }
NpgsqlDataSource _dataSource = default!;
Customer _single = default!;
int _rows;
[GlobalSetup]
public void Setup()
{
// Small: 1000 rows of ~300 B, Large: 100 rows of ~30 KB (above the 8 KB default read buffer).
var (rows, orders) = Size == PayloadSize.Small ? (1000, 1) : (100, 200);
_rows = rows;
var builder = new NpgsqlDataSourceBuilder(BenchmarkEnvironment.ConnectionString);
builder.UseJsonNet();
_dataSource = builder.Build();
var values = Enumerable.Range(0, rows).Select(i => JsonConvert.SerializeObject(Customer.Create(i, orders))).ToArray();
_single = Customer.Create(0, orders);
using var conn = _dataSource.OpenConnection();
using (var cmd = new NpgsqlCommand("DROP TABLE IF EXISTS jsonnet_bench; CREATE TABLE jsonnet_bench (data jsonb NOT NULL)", conn))
cmd.ExecuteNonQuery();
using (var cmd = new NpgsqlCommand("INSERT INTO jsonnet_bench SELECT v::jsonb FROM unnest(@values) v", conn))
{
cmd.Parameters.AddWithValue("values", values);
cmd.ExecuteNonQuery();
}
}
[GlobalCleanup]
public void Cleanup() => _dataSource.Dispose();
[Benchmark]
public async Task<int> ReadPocoAsync()
{
await using var cmd = _dataSource.CreateCommand("SELECT data FROM jsonnet_bench");
await using var reader = await cmd.ExecuteReaderAsync();
var count = 0;
while (await reader.ReadAsync())
count += (await reader.GetFieldValueAsync<Customer>(0)).Orders.Count;
return count;
}
[Benchmark]
public int ReadPocoSync()
{
using var cmd = _dataSource.CreateCommand("SELECT data FROM jsonnet_bench");
using var reader = cmd.ExecuteReader();
var count = 0;
while (reader.Read())
count += reader.GetFieldValue<Customer>(0).Orders.Count;
return count;
}
[Benchmark]
public async Task<int> ReadJObjectAsync()
{
await using var cmd = _dataSource.CreateCommand("SELECT data FROM jsonnet_bench");
await using var reader = await cmd.ExecuteReaderAsync();
var count = 0;
while (await reader.ReadAsync())
count += (await reader.GetFieldValueAsync<JObject>(0)).Count;
return count;
}
// Writes the same number of values as the read benchmarks read, as parameters of one command.
[Benchmark]
public async Task<int> WritePocoAsync()
{
await using var batch = _dataSource.CreateBatch();
for (var i = 0; i < Math.Min(_rows, 100); i++)
{
var command = new NpgsqlBatchCommand("SELECT length($1::text)");
command.Parameters.Add(new NpgsqlParameter { Value = _single, DataTypeName = "jsonb" });
batch.BatchCommands.Add(command);
}
await using var reader = await batch.ExecuteReaderAsync();
var count = 0;
do
{
while (await reader.ReadAsync())
count += reader.GetInt32(0);
} while (await reader.NextResultAsync());
return count;
}
public sealed class Customer
{
public Guid Id { get; set; }
public string Name { get; set; } = "";
public string Email { get; set; } = "";
public DateTime CreatedAt { get; set; }
public bool IsActive { get; set; }
public List<string> Tags { get; set; } = [];
public Address Address { get; set; } = new();
public List<Order> Orders { get; set; } = [];
public static Customer Create(int i, int orders) => new()
{
Id = new Guid(i, 0, 0, new byte[8]),
Name = $"Customer {i}",
Email = $"customer{i}@example.com",
CreatedAt = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMinutes(i),
IsActive = i % 2 == 0,
Tags = ["alpha", "beta", "gamma"],
Address = new() { Street = $"{i} Main Street", City = "Springfield", Country = "US" },
Orders = Enumerable.Range(0, orders).Select(o => new Order
{
Number = $"ORD-{i}-{o}", Total = o * 10.5m, Lines = [new() { Sku = "SKU-1", Quantity = 2 }, new() { Sku = "SKU-2", Quantity = 1 }]
}).ToList()
};
}
public sealed class Address
{
public string Street { get; set; } = "";
public string City { get; set; } = "";
public string Country { get; set; } = "";
}
public sealed class Order
{
public string Number { get; set; } = "";
public decimal Total { get; set; }
public List<OrderLine> Lines { get; set; } = [];
}
public sealed class OrderLine
{
public string Sku { get; set; } = "";
public int Quantity { get; set; }
}
}Metadata
Metadata
Assignees
Labels
No labels
Activity