Repository navigation
Open
Open
Copy link
Labels
Performance 📈Issues that are targeted to performance improvements.
Description
Given two identical tables other than a column defined as either JSON or VARCHAR(MAX), reading the same data from the JSON column appears to be 5-6 times slower than from the VARCHAR column.
To reproduce
using System.Text.Json;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Microsoft.Data.SqlClient;
BenchmarkRunner.Run<SqlJsonTest>();
[MemoryDiagnoser]
public class SqlJsonTest
{
private readonly SqlConnection _sqlConnection;
public SqlJsonTest()
{
_sqlConnection = new SqlConnection("Server=(local);Database=SqlJsonBenchmark;Trusted_Connection=True;TrustServerCertificate=true");
_sqlConnection.Open();
string[] tables =
[
"ItemJson",
"ItemVarchar"
];
foreach (string table in tables)
{
string tagsColumn = table.EndsWith("Varchar")
? "VARCHAR(MAX) COLLATE Latin1_General_100_BIN2_UTF8 NOT NULL"
: "JSON NOT NULL";
var createTableCommand = _sqlConnection.CreateCommand();
createTableCommand.CommandText = $"""
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.{table}') AND type in (N'U'))
DROP TABLE dbo.{table};
CREATE TABLE {table} (
Id INT IDENTITY(1,1) PRIMARY KEY,
Title VARCHAR(200) NOT NULL,
strings {tagsColumn}
);
""";
_ = createTableCommand.ExecuteNonQuery();
}
foreach (string table in tables)
{
for (int i = 0; i < 500; i++)
{
var insertCommand = _sqlConnection.CreateCommand();
insertCommand.CommandText = $"""
INSERT INTO {table} (Title, strings)
VALUES (@Title, @strings);
""";
_ = insertCommand.Parameters.AddWithValue("@Title", $"Entry {i}");
string[] tags = [.. Enumerable.Range(1, 20).Select(j => new string($"tag{j}"))];
_ = insertCommand.Parameters.AddWithValue("@strings", JsonSerializer.Serialize(tags));
_ = insertCommand.ExecuteNonQuery();
}
}
}
[Benchmark]
public Entry[] ReadEntriesJson()
{
var selectCommand = _sqlConnection.CreateCommand();
selectCommand.CommandText = $"SELECT Id, Title, strings FROM ItemJson";
using var reader = selectCommand.ExecuteReader();
var entries = new List<Entry>();
while (reader.Read())
{
int id = reader.GetInt32(0);
string title = reader.GetString(1);
var tagsJson = reader.GetSqlJson(2);
string[] tags = JsonSerializer.Deserialize<string[]>(tagsJson.Value) ?? [];
entries.Add(new Entry { Id = id, Title = title, Tags = tags });
}
return [.. entries];
}
[Benchmark(Baseline = true)]
public Entry[] ReadEntriesVarchar()
{
var selectCommand = _sqlConnection.CreateCommand();
selectCommand.CommandText = $"SELECT Id, Title, strings FROM ItemVarchar";
using var reader = selectCommand.ExecuteReader();
var entries = new List<Entry>();
while (reader.Read())
{
int id = reader.GetInt32(0);
string title = reader.GetString(1);
string tagsJson = reader.GetString(2);
string[] tags = JsonSerializer.Deserialize<string[]>(tagsJson) ?? [];
entries.Add(new Entry { Id = id, Title = title, Tags = tags });
}
return [.. entries];
}
}
public class Entry
{
public int Id { get; set; }
public required string Title { get; set; }
public required string[] Tags { get; set; }
}Actual behaviour
// * Summary *
BenchmarkDotNet v0.15.2, Windows 11 (10.0.26120.4741)
Unknown processor
.NET SDK 10.0.100-preview.6.25358.103
[Host] : .NET 10.0.0 (10.0.25.35903), X64 RyuJIT AVX2
DefaultJob : .NET 10.0.0 (10.0.25.35903), X64 RyuJIT AVX2
| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Allocated | Alloc Ratio |
|------------------- |-----------:|---------:|---------:|------:|--------:|--------:|--------:|----------:|------------:|
| ReadEntriesJson | 2,516.4 us | 30.39 us | 31.21 us | 5.82 | 0.13 | 58.5938 | 39.0625 | 1.11 MB | 1.04 |
| ReadEntriesVarchar | 432.8 us | 7.77 us | 8.32 us | 1.00 | 0.03 | 59.0820 | 38.5742 | 1.07 MB | 1.00 |
Expected behaviour
Similar, if not better, performance for reading JSON.
Further technical details
Microsoft.Data.SqlClient version: 6.1.0-preview2.25178.5
.NET target: 10.0.100-preview.6.25358.103
SQL Server version: SQL Server 2025 (17.0.800.3)
Operating system: Windows 11 (10.0.26120.4741)
Discussion
Is this perhaps due to the cost of parsing JSON every time a SqlJson instance is created?
SqlClient/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlTypes/SqlJson.cs
Lines 38 to 43 in 27aaa9e
| // Ask JsonDocument to parse it for validity, or throw. | |
| // | |
| // Note that we do not support trailing commas or comments in the | |
| // JSON. | |
| // | |
| JsonDocument.Parse(jsonString).Dispose(); |
Reacted by Maximilian Haru Raditya
Metadata
Metadata
Assignees
Labels
Performance 📈Issues that are targeted to performance improvements.
Type
Projects
- StatusShow more project fieldsBacklog
Activity
apoorvdeshmukh commentedon Jul 22, 2025
Storage layout of varchar(max) and JSON column differs significantly at the server side. There may be some conversion happening from the native storage layout to the format expected on the TDS and that may be causing this performance issue. I need to check.
I'll investigate this with the server team and update my findings here.
JsonDocument.Parsedoesn't seem to be causing this issue as I see similar numbers without it as well.frankbuckley commentedon Jul 22, 2025
Thank you!
I would imagine this might depend on the size of the JSON payload.
Out of curiosity, why does
SqlJsonvalidate the JSON?If it is invalid, the server will generate an error. This would be consistent with what happens if you attempt to (say) set a
varchar(10)column to something longer or if a column constraint is not satisfied. And, when reading, presumably you trust the server not to be returning invalid JSON.frankbuckley commentedon Jul 22, 2025
A modest payload gives me a notable difference (279x) on this simple benchmark ---
frankbuckley commentedon Jul 22, 2025
Seems worse with large payload of floats (8.7x) ---
This also suggests the 50x read improvement claimed in the release notes may be more to do with the (not so good) performance of
SqlJsonthan the performance ofSqlVector(which appears to be ~5.6x faster than deserializing an array of 1024 floats from a JSON string)?Benchmark:
[-]Reading JSON column appears to be 5x to 6x slower than reading VARCHAR(MAX) column[/-][+]Reading JSON column appears to be 5x to 8x slower than reading VARCHAR(MAX) column[/+]Address second round of review feedback
priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
Area\JsonAnalysis
The issue reports that reading
JSONcolumns viaSqlDataReader.GetSqlJsonis 5–8x (and in some payload shapes, much more) slower and allocates more than reading equivalentVARCHAR(MAX)data. Follow-up investigation by a maintainer (@apoorvdeshmukh) points to server-side storage/TDS conversion differences, while the reporter's own micro-benchmarks show theSqlJson(string)constructor'sJsonDocument.Parse(...).Dispose()validation call is extremely expensive (up to ~279x slower than skipping validation) and is likely the dominant cost on the client side for every value materialized throughGetSqlJson. This also potentially undermines the JSON/SqlVectorread performance claims in the v6.1.0-preview2 release notes. Given the measured magnitude and that it affects a documented public API path (SqlDataReader.GetSqlJson), this is a P1/P2 performance defect worth deeper investigation.Next Steps
SqlJson's constructor validation path insrc/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlTypes/SqlJson.cs— specifically whetherJsonDocument.Parse(jsonString).Dispose()can be replaced with a cheaper validation strategy (e.g.,Utf8JsonReader-based structural validation without building a fullJsonDocument, or deferring/skipping validation for values known to originate from the server, which is already assumed well-formed).TdsParser/reader code paths performing extra buffering or encoding conversions for theJSONTDS type contribute additional overhead versusVARCHAR(MAX), as suggested by the maintainer's server-side storage layout comment.Utf8JsonReader.TryParse/JsonReaderOptionsvalidation-only mode against the existingJsonDocument.Parseapproach to quantify potential savings before implementing a fix.SqlJsonperformance regression.