Skip to content

Avoid unnecessary allocations when splitting binary XML text - #136765

Merged
stephentoub merged 1 commit into
mainfrom
stephentoub-binary-xml-insertion-recovery
Nov 1, 2026
Merged

stephentoub merged 1 commit into
mainfrom
stephentoub-binary-xml-insertion-recovery

Conversation

@stephentoub

@stephentoub stephentoub commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

The insertion check was using the five-byte source buffer's length instead of the backing buffer's capacity, so every split allocated a replacement. Check the backing buffer instead and put the continuation header on the stack.

@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.

@stephentoub
stephentoub enabled auto-merge (squash) October 31, 2026 21:45
private void InsertNode(XmlBinaryNodeType nodeType, int length)
{
byte[] buffer = new byte[5];
Span<byte> buffer = stackalloc byte[1 + sizeof(int)];

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: = [0, 0, 0, 0, 0] will avoid an unsafe{} here.

I know it doesn't look pretty, but we have no other good option to avoid unsafe (unless you disable SkipLocalsInit for System.Private.DataContractSerialization)

@EgorBo EgorBo Oct 31, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Funny enough, = [0, 0, 0, 0, 0] emits a better codegen than stackalloc byte[1 + sizeof(int)]; 😐 (no gs cookie) https://godbolt.org/z/9KdPT66r9

@stephentoub stephentoub Nov 1, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

will avoid an unsafe{} here

What unsafe?

no gs cookie

We've been talking about that for years. That's either a hole the JIT should fix, or it should also avoid it for this const stackalloc case. I'm not aware of any fundamental reason those should differ.

We're not really advocating going through the libraries and replacing such stackalloc's with [0, ..., 0], are we?

@EgorBo EgorBo Nov 1, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

will avoid an unsafe{} here

What unsafe?

https://github.com/dotnet/csharplang/blob/main/proposals/unsafe-evolution.md#stack-allocation

the compiler can't prove you overwrite/don't consume undefined values.

We've already started the migration, see #136664

That's either a hole the JIT should fix, or it should also avoid it for this const stackalloc case. I'm not aware of any fundamental reason those should differ.

My point was more about perf concern of that replacement if you had any.

We're not really advocating going through the libraries and replacing such stackalloc's with [0, ..., 0], are we?

I don't see anything wrong with small buffers like up to 4-5 elements, the readability isn't bad + no unsafe {} (or InlineArray5?). After the automatic migration (November) your code will be converted into:

            scoped Span<byte> buffer;
            // SAFETY: To be audited
            unsafe
            {
                buffer= stackalloc byte [1 + sizeof(int)];
            }

so technically this change replaces safe code with unsafe (just not at the very moment).

@stephentoub stephentoub Nov 1, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

the compiler can't prove you overwrite/don't consume undefined values.

Your concern is the lack of zero init?

First, the compiler should actually be able to prove that in this case; this isn't a case of it not being able to if we wanted it to, this is a case of wanting rules that apply in other cases to consistently apply to a case like this as well.

Also, this is a const-sized stackalloc. From the compiler's perspective, it is equivalent to a fixed length initializer. If your recommendation for any such stackalloc is going to be zero-initializing it with syntax like [0, ..., 0] in order to avoid unsafe, you should instead just drop the SkipLocalsInit from the library.

Personally, I think we're in the wrong by saying this case must be unsafe. There is nothing inherently unsafe about random bytes here.

I don't see anything wrong with small buffers like up to 4-5 elements, the readability isn't bad + no unsafe {}

It's about developers needing to a remember a bazillion rules about one thing being subtly better than another, but only in certain cases, certain lengths, use this one here, use that one there... we're making this unnecessarily complicated, encouraging churn for reasons that shouldn't exist.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

reading stack garbage from structs' paddings as bytes is fully safe too (e.g. ROS MemoryMarshal.AsBytes should be made back caller-safe)

The purist perspective inspired by Rust was valuable in getting the memory safety project off the ground and establish the principles. As we are learning by applying our current design to large amounts of real-world code, we should shift our focus toward a more pragmatic question when creating case-laws for the gray areas: what actually helps developers and agents write correct, secure C# code? I think MemoryMarshal.AsBytes should stay as unsafe with that in mind. Yes, there will be inconsistencies and I think that's fine.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Well the question is - is it worth introducing this inconsistency in the first place? or those who relies on SkipLocalsInit (it already requires AllowUnsafeBlocks) will just slap a comment // SAFETY: the buffer is fully initialized by the following code. or just avoid unitialized buffers & potentially avoid problems those might cause.

@jkotas jkotas Nov 1, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We are always going to have inconsistency since we cannot afford to disallow global state that acts as unsafe escape hatch.

If we keep going with purist perspective exclusively, disallow all ways to get uninitialized scratch byte buffers from safe code and keep telling everyone to avoid unsafe code at the same time, I worry we are going to see emergence of per-library static byte buffer pools since you can make those using 100% safe code. It won't help with safety (the byte buffers from a pool have unpredictable state just like stack allocated byte buffers) and hurt performance of the system as a whole (trivial local pools do great on microbenchmarks).

@EgorBo EgorBo Nov 1, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Do we want to enable just byte? or any primitive except for bool (and float/double)?
e.g. stackalloc char is only 3x less popular than stackalloc byte (same for int). Do we want to explain why bool is unsafe?

And we still haven't touched exposing stack data. utf8/utf16 (byte/char) could be problematic when initialized out of garbage as well? (cc @GrabYourPitchforks).
Also, a scratch buffer initialized with garbage might be problematic when the reciever expects zero-termination (but that involves unsafe anyway).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'm on vacation, so I'd appreciate it if someone could move this forward as a C# proposal or change if we agree on it.

@stephentoub
stephentoub merged commit 7588419 into main Nov 1, 2026
90 checks passed
@stephentoub
stephentoub deleted the stephentoub-binary-xml-insertion-recovery branch November 1, 2026 01:18
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants