Repository navigation
CborWriter: skip map key bookkeeping in Lax mode - #137772
Merged
bartonjs merged 5 commits intoNov 18, 2026
Merged
Conversation
|
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. |
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-formats-cbor, @bartonjs, @vcsjones |
Contributor
Author
|
@dotnet-policy-service agree company="Amazon" |
bartonjs
reviewed
Nov 17, 2026
…ecks at map start
Contributor
There was a problem hiding this comment.
🟡 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
approved these changes
Nov 18, 2026
bartonjs
enabled auto-merge (squash)
November 18, 2026 19:16
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.

Description
CborWriterrecords 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 callsHandleMapKeyWrittenorHandleMapValueWritten, on every map start it sets_currentKeyOffset, and on every map end it callsCompleteMapWrite. Separately, a few conformance mode checks (RequiresUniqueKeys,RequiresSortedKeys,RequiresDefiniteLengthItems,GetUtf8Encoding) are switch statements onConformanceModeevaluated on hot paths, although the mode is fixed at construction.This PR:
_tracksMapKeys(RequiresUniqueKeys || RequiresSortedKeys, sofalseonly in Lax)._tracksMapKeysisfalse, skips the key and value offset updates inAdvanceDataItemCounters, the_currentKeyOffsetassignment at map start, andCompleteMapWriteat map end.StackFrameandPushDataItem/PopDataItem's save and restore are unchanged. In Lax the key and value offsets staynull, 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:
HandleMapKeyWrittenandHandleMapValueWrittendo work beyond setting the offsets only underRequiresUniqueKeysorRequiresSortedKeys, bothfalsein Lax.Reset(), only those two methods use the key and value offsets.CompleteMapWritesorts only when_keysRequireSortingis set, which happens only underRequiresSortedKeys. 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.
mainand 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 isCborConformanceMode.Lax(Strict for DocStrict) withconvertIndefiniteLengthEncodings: true, created once and reused throughReset().{"S": v}, indefinite length, per mapDocStrict 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 likek: {"S": v}ork: {"N": v}plus"nested": {"M": {...}}with 4 morek: {"S": v}entries: 28 maps, all started withWriteStartMap(null), and 77 short strings (389 bytes), thenEncode(Span<byte>)into a preallocated buffer.The Map1Def loop:
Testing
main. The 2 skipped tests are theRemoteExecutorculture tests, which I couldn't run locally.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 andAllowMultipleRootLevelValueson 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,BytesWrittenandIsWriteCompletedmatched, and so did the finalEncode()bytes: 0 differences.