Skip to content

Conversation

@MihaZupan
Copy link
Member

@MihaZupan MihaZupan commented Jun 3, 2024

Same idea as #102859, but for StringContent. Saves the 5 smaller allocations each time.

AFAICT UTF-8 is practically the only encoding used here, with text/plain (default) and application/json being by far the most common media types. This PR special-cases these two combinations.

[Benchmark] public void Test() { var content = new StringContent("Foo", Encoding.UTF8, "application/json"); foreach (var header in content.Headers.NonValidated) { _ = header.Value.ToString(); } }
Method Toolchain Mean Error Ratio Allocated Alloc Ratio
Test main 296.5 ns 2.95 ns 1.00 520 B 1.00
Test pr 147.2 ns 0.55 ns 0.50 304 B 0.58
@dotnet-policy-service
Copy link
Contributor

Tagging subscribers to this area: @dotnet/ncl
See info in area-owners.md if you want to be subscribed.


if (knownValue is not null)
{
Headers.TryAddWithoutValidation(KnownHeaders.ContentType.Descriptor, knownValue);
Copy link
Member

Choose a reason for hiding this comment

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

Will Header.ContentType be populated in this case?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, behavior-wise as far as the user can see, the two should be the same.

The ContentType property uses the underlying dictionary as the source of truth / storage, and will lazily parse the value when first accessed.

@MihaZupan MihaZupan merged commit b2601ed into dotnet:main Jun 6, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Jul 7, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

3 participants