Skip to content

CborWriter: skip map key bookkeeping in Lax mode - #137772

Merged
bartonjs merged 5 commits into
dotnet:mainfrom
sichanyoo:cbor-writer-lax-skip-key-tracking
Nov 18, 2026
Merged

bartonjs merged 5 commits into
dotnet:mainfrom
sichanyoo:cbor-writer-lax-skip-key-tracking

Conversation

@sichanyoo

Copy link
Copy Markdown
Contributor

Description

CborWriter records the offset of every map key and value so that Strict and the canonical modes can check for duplicate and unsorted keys. Lax mode does neither check, but it still pays for the bookkeeping: on every item written inside a map it calls HandleMapKeyWritten or HandleMapValueWritten, on every map start it sets _currentKeyOffset, and on every map end it calls CompleteMapWrite. Separately, a few conformance mode checks (RequiresUniqueKeys, RequiresSortedKeys, RequiresDefiniteLengthItems, GetUtf8Encoding) are switch statements on ConformanceMode evaluated on hot paths, although the mode is fixed at construction.

This PR:

  • Caches those four checks in readonly fields set in both constructors, plus _tracksMapKeys (RequiresUniqueKeys || RequiresSortedKeys, so false only in Lax).
  • When _tracksMapKeys is false, skips the key and value offset updates in AdvanceDataItemCounters, the _currentKeyOffset assignment at map start, and CompleteMapWrite at map end.

StackFrame and PushDataItem/PopDataItem's save and restore are unchanged. In Lax the key and value offsets stay null, so saving and restoring them is a no-op. (#137111 also proposes restructuring the frame; that is a separate PR.)

There are no public API changes.

Why the behavior is the same

In Lax mode, the skipped code only fed the duplicate and sorted key checks:

  • HandleMapKeyWritten and HandleMapValueWritten do work beyond setting the offsets only under RequiresUniqueKeys or RequiresSortedKeys, both false in Lax.
  • Apart from the frame save and restore and Reset(), only those two methods use the key and value offsets.
  • CompleteMapWrite sorts only when _keysRequireSorting is set, which happens only under RequiresSortedKeys. It returns the key range collections to their pools only when they were created, which happens only under the two checks.

Strict, Canonical and Ctap2Canonical run the same code as before.

Benchmarks

BenchmarkDotNet 0.15.2, .NET 10.0.12, Arm64 RyuJIT, Apple M1 Pro, macOS 26.7.3. main and this branch were built from source in the same benchmark project (namespace changed, nothing else) and run as separate processes in 3 interleaved rounds, alternating which went first. Each column is the best mean of the 3 rounds. The writer is CborConformanceMode.Lax (Strict for DocStrict) with convertIndefiniteLengthEncodings: true, created once and reused through Reset().

Benchmark main this PR this PR vs main
Text: 64 short strings in an array, per string 11.3 ns 10.6 ns 1.07x faster
Pairs: 32 short string pairs in a map, per string 12.8 ns 10.6 ns 1.21x faster
Map1Indef: 64 maps {"S": v}, indefinite length, per map 45.4 ns 38.8 ns 1.17x faster
Map1Def: same, definite length, per map 40.3 ns 33.2 ns 1.21x faster
Doc: nested document (below) 1,598 ns 1,331 ns 1.20x faster
DocStrict: Doc with unique keys, Strict mode 2,194 ns 2,122 ns 1.03x faster

DocStrict varied by up to 8% across rounds of main (2,194 to 2,368 ns), so its 1.03x is within noise. Allocations are unchanged: 0 B for Text, Pairs and Map1, 128 B for Doc and DocStrict (the benchmark's own key strings).

Doc is {"TableName": "my-table", "Item": {...}}, where Item has 20 short-key entries like k: {"S": v} or k: {"N": v} plus "nested": {"M": {...}} with 4 more k: {"S": v} entries: 28 maps, all started with WriteStartMap(null), and 77 short strings (389 bytes), then Encode(Span<byte>) into a preallocated buffer.

The Map1Def loop:

// values: 64 ASCII strings of 1 to 9 characters. Reported per map (OperationsPerInvoke = 64).
var writer = new CborWriter(CborConformanceMode.Lax, convertIndefiniteLengthEncodings: true); // created once

writer.Reset();
writer.WriteStartArray(64);
for (int i = 0; i < 64; i++)
{
    writer.WriteStartMap(1);           // Map1Indef: WriteStartMap(null)
    writer.WriteTextString("S");
    writer.WriteTextString(values[i]);
    writer.WriteEndMap();
}
writer.WriteEndArray();

Testing

  • System.Formats.Cbor.Tests (net10.0 configuration, including the FsCheck property tests): 2,652 passed, 2 skipped, 0 failed, the same as main. The 2 skipped tests are the RemoteExecutor culture tests, which I couldn't run locally.
  • Differential comparison against main, as described in CborWriter: reduce per-call overhead of map and array bookkeeping #137111. Boundary test: 1,512 documents with container sizes and string lengths around 24 and 256, in every conformance mode with conversion on and off. Fuzz: random sequences of the write APIs with misuse mixed in, 10,000 cases per configuration over all four conformance modes, conversion and AllowMultipleRootLevelValues on and off, with both a reused writer and a new writer per case. That is 121,581,530 calls per comparison. After every call, success or exception (type and message), CurrentDepth, BytesWritten and IsWriteCompleted matched, and so did the final Encode() bytes: 0 differences.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-formats-cbor, @bartonjs, @vcsjones
See info in area-owners.md if you want to be subscribed.

@sichanyoo

Copy link
Copy Markdown
Contributor Author

@dotnet-policy-service agree company="Amazon"

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Map-start methods still assign _currentKeyOffset unconditionally, so Lax maps retain key-offset bookkeeping contrary to the stated null-offset invariant.

1 open issue
What changed in this PR

This PR reduces CborWriter overhead by caching fixed conformance settings and skipping map-key processing in Lax mode. It implements a focused portion of #137111 without changing public APIs or restructuring stack frames.

Changes:

  • Cache key-validation, definite-length, and UTF-8 encoding settings in both constructors.
  • Skip per-item map-key bookkeeping and map-completion work in Lax mode.
  • Use cached settings when writing maps, arrays, and strings.
File Description
src/​libraries/​System.Formats.Cbor/​src/​System/​Formats/​Cbor/​Writer/​CborWriter.String.cs Uses cached UTF-8 encoding and definite-length requirements.
src/​libraries/​System.Formats.Cbor/​src/​System/​Formats/​Cbor/​Writer/​CborWriter.Map.cs Uses cached uniqueness, sorting, and definite-length requirements.
src/​libraries/​System.Formats.Cbor/​src/​System/​Formats/​Cbor/​Writer/​CborWriter.cs Initializes cached settings and gates map bookkeeping.
src/​libraries/​System.Formats.Cbor/​src/​System/​Formats/​Cbor/​Writer/​CborWriter.Array.cs Uses the cached definite-length requirement.

Review effort: Balanced

@bartonjs
bartonjs enabled auto-merge (squash) November 18, 2026 19:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Formats.Cbor community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants