Repository navigation
Conversation
- Split on newlines without a regex and without allocating substrings. - Skip directly to chars that may change the internal state (vectorized via SearchValues on net8.0+). - Escape quoted text in a single pass instead of O(n^2) string concatenation. - Track the last written char instead of indexing into the StringBuilder. - Avoid LINQ and small allocations on hot paths. - Add a BenchmarkDotNet project.
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.
Adds a BenchmarkDotNet project (
CodeBlockWriterSharp.Benchmarks) and makes writing 1.7x to 58x faster with about half the allocations. The output is unchanged.Results
BenchmarkDotNet default job, .NET 10:
Run them with:
Changes
IndexOf('\n')instead ofRegex.Split, and append ranges of the original string instead of substrings.net8.0, where this uses a vectorizedSearchValues<char>search. Thenetstandard2.0build uses a simple loop.Quote(text): escaping was O(n²) because it built the result withstring +=. It's now a single pass that returns the original string when there's nothing to escape. The quotes are written separately instead of concatenated. Removed the now unusedStringUtils.EscapeChar.StringBuilderfor every write and newline.Count > 0instead of LINQAny()inIsInString(), oneAppend(char, count)for indentation, and cached strings for the quote char,Space()andTab().Verification
EscapeForWithinStringcases for\r\nand empty input.\r\n, blocks and indentation. It also wrote a large real-world generated TypeScript file. It recorded the output plusIsInString/IsInComment/IsLastNewLine/etc. after every call. The log hash was identical tomainfor both thenetstandard2.0andnet8.0builds, and it differed for the build before the regex fix, so the harness does catch real differences.