Reduce allocation in TextWriter.NewLine#121508
Merged
stephentoub merged 3 commits intodotnet:mainfrom Nov 17, 2025
Merged
Conversation
Contributor
|
Tagging subscribers to this area: @dotnet/area-system-io |
It's reasonably common for a codebase to pick a specific newline string and set it regardless of OS, but currently that ends up allocating on every OS. Two changes: 1. When setting TextWriter.NewLine to the existing value, make it a nop to avoid unnecessarily calling ToCharArray. 2. When setting TextWriter.NewLine to "\n" on Windows or to "\r\n" on Unix, use a cached array.
Contributor
There was a problem hiding this comment.
Pull Request Overview
This PR optimizes TextWriter.NewLine setter to reduce allocations in common scenarios where codebases set a specific newline string regardless of OS. The changes include:
- Making the setter a no-op when setting to the same value
- Caching arrays for "\n" and "\r\n" (the non-default OS newline strings)
jozkee
approved these changes
Nov 10, 2025
GerardSmit
reviewed
Nov 10, 2025
This was referenced Nov 11, 2025
Open
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 subscribe to this conversation on GitHub.
Already have an account?
Sign in.
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.
It's reasonably common for a codebase to pick a specific newline string and set it regardless of OS, but currently that ends up allocating on every OS each call to set_NewLine.
Two changes: