Skip to content

perf: avoid line allocations when writing generated source - #6781

Merged
thomhurst merged 1 commit into
mainfrom
perf/generator-raw-text
Sep 11, 2026
Merged

thomhurst merged 1 commit into
mainfrom
perf/generator-raw-text

Conversation

@thomhurst

@thomhurst thomhurst commented Sep 11, 2026

Copy link
Copy Markdown
Owner

CodeWriter.AppendRaw splits every generated fragment into an array of line strings and trims each string before writing it. The per-class test-metadata pipeline calls it repeatedly while assembling generated source.

Scan the original string and append each line directly with StringBuilder.Append(string, startIndex, count). Defer blank lines until the next content line so leading/trailing blank lines remain omitted and interior blank lines remain intact. Preserve indentation, partial-line writes, CR/LF/CRLF handling, and Unicode trailing-whitespace trimming. Generated source is unchanged.

BenchmarkDotNet 0.15.8 results using actual baseline (b43fecac6d) and modified generator assemblies:

Workload Before mean After mean Before allocated After allocated
Write a 300-line generated fragment 25.726 μs 8.872 μs 66.34 KB 35.75 KB
TestMetadataGenerator, 10,000 bare tests 169.0 ms 110.4 ms 178.55 MB 162.47 MB
TestMetadataGenerator, 10,000 inline-data tests 239.5 ms 224.8 ms 384.87 MB 358.63 MB

The writer is about 2.9× faster and allocates 46% less in its focused workload. The complete metadata-generation passes allocate approximately 9% and 7% less. Timing varies in the larger workloads, and the inline-data confidence intervals overlap; its timing improvement is inconclusive. These measurements exclude parsing and compiling generated code, so they do not establish a whole-build speedup.

Validation:

  • 134 generator tests pass, with one existing skip and no snapshot changes.
  • All 12 new formatting cases pass on .NET 10 and .NET Framework 4.7.2.
  • 1,000 randomized sequences of three writer calls match the baseline output exactly.
  • Benchmark setup verifies identical generated filenames and source text for all 100 classes in each 10,000-test workload.
  • Roslyn 4.4 and 4.14 variant builds pass with zero warnings/errors.

The PR comment includes full benchmark reports, confidence intervals, source, and reproduction commands. Environment: Windows 11, i7-12700K, .NET 10.0.12, SDK 11.0.100-preview.7.26381.103; 15 measured iterations, 6 warmups, 1 launch. Generator passes use one full suite per iteration.

Summary by CodeRabbit

  • Bug Fixes

    • Preserved raw text formatting, including indentation, blank lines, trailing whitespace handling, partial lines, and mixed newline formats.
  • Tests

    • Added coverage for empty input, Unicode whitespace, formatting normalization, and combining raw text with subsequent writes.

@thomhurst
thomhurst deployed to Pull Requests September 11, 2026 15:21 — with GitHub Actions Active
@thomhurst
thomhurst deployed to Pull Requests September 11, 2026 15:21 — with GitHub Actions Active
@thomhurst
thomhurst deployed to Pull Requests September 11, 2026 15:21 — with GitHub Actions Active
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 11, 2026

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review Completed 2026-09-11T15:24:12.390494Z 3819819 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Sep 11, 2026

Copy link
Copy Markdown

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: d252b8af-542d-4e42-97ba-21ecf167c267

📥 Commits

Reviewing files that changed from the base of the PR and between b43feca and 3819819.

📒 Files selected for processing (2)
  • src/TUnit.Core.SourceGenerator/CodeWriter.cs
  • tests/TUnit.Core.SourceGenerator.Tests/CodeWriterTests.cs

Included review availability: Your plan provides up to 8 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

CodeWriter.AppendRaw now scans input character by character. It preserves formatting behavior while handling whitespace, blank lines, indentation, partial lines, and mixed newline sequences. Tests cover these cases and empty input.

Changes

AppendRaw formatting

Layer / File(s) Summary
AppendRaw scanning and validation
src/TUnit.Core.SourceGenerator/CodeWriter.cs, tests/TUnit.Core.SourceGenerator.Tests/CodeWriterTests.cs
AppendRaw trims line whitespace, preserves interior blank lines, applies indentation, and avoids intermediate string splitting. Tests cover formatting, partial lines, subsequent writes, mixed newlines, and empty input.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~15 minutes

Change: Refactor

Merge Risk: ⚪ Minimal · up to 38198

The AppendRaw rewrite preserves its tested formatting and write-state behavior, with no current merge-blocking risk identified.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: reducing line allocations in generated-source writing. It matches the AppendRaw implementation changes and the stated performance objective…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perf/generator-raw-text

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit checks each line with care
Blank rows wait in tidy air
Whitespace fades, interiors stay
Newlines march in one array
Tests hop after writes complete

Comment @coderabbitai help to get the list of available commands.

@thomhurst

Copy link
Copy Markdown
Owner Author

Reproduction and full evidence

The benchmark loads the actual generator assemblies into separate AssemblyLoadContext instances, sharing Roslyn 4.14.0. Module IDs:

  • Baseline b43fecac6d: 956c98a2-7b0e-4cb5-9431-1a7ede106632
  • Modified: 51c2ae90-69d0-4b8d-9ad2-98c2279f8b46

Build src/TUnit.Core.SourceGenerator/TUnit.Core.SourceGenerator.csproj -c Release at each revision and copy the resulting netstandard2.0/TUnit.Core.SourceGenerator.dll to before/ or after/ in a standalone RawGeneratorBench directory. Copy the repository's global.json and a locally built TUnit.Core.dll to the directory root. This run used the 99.99.99.0 Core assembly from the preceding generator experiment. Create the project and program below, then run:

dotnet run -c Release -- --filter '*' --job Dry
dotnet run -c Release --no-build -- --filter '*RawWriterBenchmarks*' --iterationCount 15 --warmupCount 6 --launchCount 1 --exporters json
dotnet run -c Release --no-build -- --filter '*MetadataGeneratorBenchmarks*' --iterationCount 15 --warmupCount 6 --launchCount 1 --invocationCount 1 --unrollFactor 1 --exporters json

The writer workload includes construction, writing 100 repeated three-line fragments, and converting the result to a string. Reflection and expression compilation occur only in setup; measured calls use compiled delegates. The generator workload has 100 classes with 100 tests each. Setup checks compilation errors, generator diagnostics, and exact equality of all 100 generated source files. Each measured operation runs the generator from the initial driver state; returned drivers are not retained, so it does not benchmark cached no-op generation. Parsing and initial compilation validation occur outside measurement.

Regression commands:

dotnet build src/TUnit.Core/TUnit.Core.csproj -c Release -f netstandard2.0
dotnet run --project tests/TUnit.Core.SourceGenerator.Tests -c Release -f net10.0
dotnet run --project tests/TUnit.Core.SourceGenerator.Tests -c Release -f net472 -- --treenode-filter '/*/*/CodeWriterTests/*'
dotnet build src/TUnit.Core.SourceGenerator.Roslyn414/TUnit.Core.SourceGenerator.Roslyn414.csproj -c Release
dotnet build src/TUnit.Core.SourceGenerator.Roslyn44/TUnit.Core.SourceGenerator.Roslyn44.csproj -c Release

Results: 134 passed / 1 existing skip in the complete generator suite; 12 passed on .NET Framework 4.7.2; both variant builds passed without warnings or errors. Existing snapshots remained unchanged. The additional differential script below checked 1,000 randomized sequences against both actual assemblies, including different indentation levels, prefixes, suffixes, and Unicode whitespace; all outputs matched exactly.

Place Verify-RawWriter.ps1 alongside the RawGeneratorBench directory and run it with pwsh.

Writer results:


BenchmarkDotNet v0.15.8, Windows 11 (10.0.26200.9168/25H2/2025Update/HudsonValley2)
12th Gen Intel Core i7-12700K 3.60GHz, 1 CPU, 20 logical and 12 physical cores
.NET SDK 11.0.100-preview.7.26381.103
  [Host]     : .NET 10.0.12 (10.0.12, 10.0.1226.42308), X64 RyuJIT x86-64-v3
  Job-OWOXYI : .NET 10.0.12 (10.0.12, 10.0.1226.42308), X64 RyuJIT x86-64-v3

IterationCount=15  LaunchCount=1  WarmupCount=6  

Method Mean Error StdDev Ratio RatioSD Gen0 Gen1 Allocated Alloc Ratio
Before 25.726 μs 0.5690 μs 0.5323 μs 1.00 0.03 5.1880 0.6714 66.34 KB 1.00
After 8.872 μs 0.4066 μs 0.3804 μs 0.34 0.02 2.7924 0.1984 35.75 KB 0.54

Generator results:


BenchmarkDotNet v0.15.8, Windows 11 (10.0.26200.9168/25H2/2025Update/HudsonValley2)
12th Gen Intel Core i7-12700K 3.60GHz, 1 CPU, 20 logical and 12 physical cores
.NET SDK 11.0.100-preview.7.26381.103
  [Host]     : .NET 10.0.12 (10.0.12, 10.0.1226.42308), X64 RyuJIT x86-64-v3
  Job-NOAUNV : .NET 10.0.12 (10.0.12, 10.0.1226.42308), X64 RyuJIT x86-64-v3

InvocationCount=1  IterationCount=15  LaunchCount=1  
UnrollFactor=1  WarmupCount=6  

Method Scenario Mean Error StdDev Ratio RatioSD Gen0 Gen1 Gen2 Allocated Alloc Ratio
Before Bare 169.0 ms 31.46 ms 29.43 ms 1.03 0.24 12000.0000 5000.0000 1000.0000 178.55 MB 1.00
After Bare 110.4 ms 3.28 ms 2.56 ms 0.67 0.11 11000.0000 5000.0000 1000.0000 162.47 MB 0.91
Before InlineData 239.5 ms 37.29 ms 33.06 ms 1.02 0.18 27000.0000 7000.0000 1000.0000 384.87 MB 1.00
After InlineData 224.8 ms 24.77 ms 21.96 ms 0.95 0.14 26000.0000 9000.0000 2000.0000 358.63 MB 0.93
Benchmark project and source
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.14.0" />
    <Reference Include="TUnit.Core"><HintPath>TUnit.Core.dll</HintPath></Reference>
    <None Update="before/*.dll;after/*.dll" CopyToOutputDirectory="PreserveNewest" />
  </ItemGroup>
</Project>
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);

public static class Versions
{
    public static Assembly Load(string name)
    {
        var assembly = new AssemblyLoadContext(name).LoadFromAssemblyPath(
            Path.Combine(AppContext.BaseDirectory, name, "TUnit.Core.SourceGenerator.dll"));
        Console.WriteLine($"{name} MVID: {assembly.ManifestModule.ModuleVersionId}");
        return assembly;
    }
}

[MemoryDiagnoser]
public class MetadataGeneratorBenchmarks
{
    [Params("Bare", "InlineData")]
    public string Scenario { get; set; } = "Bare";
    private CSharpCompilation _compilation = null!;
    private GeneratorDriver _before = null!;
    private GeneratorDriver _after = null!;

    [GlobalSetup]
    public void Setup()
    {
        var trees = new List<SyntaxTree>();
        for (var c = 0; c < 100; c++)
        {
            var source = new StringBuilder("using System; using TUnit.Core; public class Tests" + c + " {");
            for (var m = 0; m < 100; m++)
            {
                source.Append("[Test]");
                source.Append(Scenario == "InlineData" ? "[Arguments(42)] public void Test" : "public void Test");
                source.Append(m).Append(Scenario == "InlineData" ? "(int value) {" : "() {");
                source.Append("int x = 42; if (x * x + 1 != 1765) throw new Exception(); }");
            }
            source.Append('}');
            trees.Add(CSharpSyntaxTree.ParseText(source.ToString()));
        }
        var references = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!).Split(Path.PathSeparator)
            .Select(p => MetadataReference.CreateFromFile(p)).ToList();
        references.Add(MetadataReference.CreateFromFile(typeof(TUnit.Core.TestAttribute).Assembly.Location));
        _compilation = CSharpCompilation.Create("SyntheticSuite", trees, references,
            new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
        var errors = _compilation.GetDiagnostics().Where(d => d.Severity == DiagnosticSeverity.Error).ToArray();
        if (errors.Length != 0) throw new InvalidOperationException(string.Join("\n", errors.Select(e => e.ToString())));
        _before = LoadDriver("before");
        _after = LoadDriver("after");
        var beforeResult = _before.RunGenerators(_compilation).GetRunResult();
        var afterResult = _after.RunGenerators(_compilation).GetRunResult();
        if (beforeResult.Diagnostics.Concat(afterResult.Diagnostics).Any(d => d.Severity == DiagnosticSeverity.Error))
            throw new InvalidOperationException("Generator diagnostics");
        var beforeSources = beforeResult.Results.Single().GeneratedSources;
        var afterSources = afterResult.Results.Single().GeneratedSources;
        if (beforeSources.Length != 100 || afterSources.Length != 100 ||
            !beforeSources.Select(s => (s.HintName, s.SourceText.ToString()))
                .SequenceEqual(afterSources.Select(s => (s.HintName, s.SourceText.ToString()))))
            throw new InvalidOperationException("Generated sources differ or are missing.");
    }

    private static GeneratorDriver LoadDriver(string name) => CSharpGeneratorDriver.Create(
        (IIncrementalGenerator)Activator.CreateInstance(Versions.Load(name).GetType(
            "TUnit.Core.SourceGenerator.Generators.TestMetadataGenerator")!)!);

    [Benchmark(Baseline = true)]
    public GeneratorDriver Before() => _before.RunGenerators(_compilation);

    [Benchmark]
    public GeneratorDriver After() => _after.RunGenerators(_compilation);
}

[MemoryDiagnoser]
public class RawWriterBenchmarks
{
    private Func<string, string> _before = null!;
    private Func<string, string> _after = null!;
    private string _text = null!;

    [GlobalSetup]
    public void Setup()
    {
        _before = LoadWriter("before");
        _after = LoadWriter("after");
        _text = string.Concat(Enumerable.Repeat("    new TestEntry(methodIndex: 42,\r\n        attributes: __Attributes),   \r\n\r\n", 100));
        if (_before(_text) != _after(_text)) throw new InvalidOperationException("Writer output differs.");
    }

    private static Func<string, string> LoadWriter(string name)
    {
        var type = Versions.Load(name).GetType("TUnit.Core.SourceGenerator.CodeWriter")!;
        var text = Expression.Parameter(typeof(string));
        var writer = Expression.Variable(type);
        var body = Expression.Block([writer],
            Expression.Assign(writer, Expression.New(type.GetConstructor([typeof(string), typeof(bool)])!,
                Expression.Constant("    "), Expression.Constant(false))),
            Expression.Call(writer, type.GetMethod("Indent")!),
            Expression.Call(writer, type.GetMethod("AppendRaw")!, text),
            Expression.Call(writer, type.GetMethod("ToString")!));
        return Expression.Lambda<Func<string, string>>(body, text).Compile();
    }

    [Benchmark(Baseline = true)]
    public string Before() => _before(_text);

    [Benchmark]
    public string After() => _after(_text);
}
Differential verification script
$ErrorActionPreference = 'Stop'
$types = foreach ($version in @('before', 'after')) {
    $context = [System.Runtime.Loader.AssemblyLoadContext]::new($version)
    $assembly = $context.LoadFromAssemblyPath((Join-Path $PSScriptRoot "RawGeneratorBench/$version/TUnit.Core.SourceGenerator.dll"))
    $assembly.GetType('TUnit.Core.SourceGenerator.CodeWriter')
}
$random = [Random]::new(20260911)
$characters = [char[]]@('a', 'b', ' ', "`t", "`r", "`n", [char]0x85, [char]0xa0, [char]0x2003, [char]0x2028, [char]0)
for ($case = 0; $case -lt 1000; $case++) {
    $indent = if ($case % 2) { '--' } else { '    ' }
    $writers = foreach ($type in $types) {
        [Activator]::CreateInstance($type, [object[]]@($indent, $false))
    }
    foreach ($writer in $writers) {
        $writer.SetIndentLevel($case % 4) | Out-Null
        if ($case % 3) { $writer.Append('prefix:') | Out-Null }
    }
    for ($fragment = 0; $fragment -lt 3; $fragment++) {
        $buffer = [char[]]::new($random.Next(0, 100))
        for ($i = 0; $i -lt $buffer.Length; $i++) {
            $buffer[$i] = $characters[$random.Next($characters.Length)]
        }
        $inputText = [string]::new($buffer)
        foreach ($writer in $writers) { $writer.AppendRaw($inputText) | Out-Null }
    }
    foreach ($writer in $writers) { $writer.Append('tail') | Out-Null }
    if (-not [string]::Equals($writers[0].ToString(), $writers[1].ToString(), [StringComparison]::Ordinal)) {
        throw "Output differs in randomized case $case."
    }
}
Write-Output 'PASS: 1,000 randomized sequences of three AppendRaw calls match baseline byte-for-byte.'

@thomhurst
thomhurst enabled auto-merge (squash) September 11, 2026 15:25
@greptile-apps

greptile-apps Bot commented Sep 11, 2026

Copy link
Copy Markdown

Greptile Summary

This PR optimizes generated-source writing by scanning multiline text directly instead of allocating an array and individual trimmed strings.

  • Appends source slices directly to the existing StringBuilder.
  • Defers blank lines to preserve interior whitespace while omitting leading and trailing blank lines.
  • Adds coverage for mixed newline formats, Unicode whitespace, partial-line writes, indentation, and sequential calls.

Confidence Score: 5/5

The PR appears safe to merge, with no actionable correctness, compatibility, security, or repository-rule issues identified.

The optimized implementation maintains the existing writer-state and formatting contracts, uses APIs supported by every configured generator target, and is covered by targeted cross-framework tests.

Important Files Changed

Filename Overview
src/TUnit.Core.SourceGenerator/CodeWriter.cs Replaces allocation-heavy splitting in AppendRaw with behaviorally equivalent indexed scanning and direct appends.
tests/TUnit.Core.SourceGenerator.Tests/CodeWriterTests.cs Adds focused regression coverage for formatting, writer state, newline variants, and whitespace edge cases.

Reviews (1): Last reviewed commit: "perf: avoid splitting raw generated sour..." | Re-trigger Greptile

@thomhurst
thomhurst merged commit f9a55a8 into main Sep 11, 2026
14 checks passed
@thomhurst
thomhurst deleted the perf/generator-raw-text branch September 11, 2026 15:52
This was referenced Sep 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant