Skip to content

Avoid quadratic VB CodeDOM overload scans - #136090

Open
marius-bughiu wants to merge 2 commits into
dotnet:mainfrom
marius-bughiu:codex/codedom-vb-overload-index
Open

marius-bughiu wants to merge 2 commits into
dotnet:mainfrom
marius-bughiu:codex/codedom-vb-overload-index

Conversation

@marius-bughiu

Copy link
Copy Markdown

VBCodeProvider scans every member of a type for each method to decide whether to emit Overloads. A generated type with thousands of uniquely named methods therefore performs quadratic name matching even though none of those methods is overloaded. This came from profiling workflow-generated VB support code; the measurements below use standalone synthetic CodeDOM graphs with unique method names.

Cache an ordinal-ignore-case overload index for types with more than 32 members. Keep the scan for smaller types, where index setup costs more. The index distinguishes repeated references from distinct same-name methods, excludes constructors and explicit interface implementations, and observes the explicit Overloaded flag directly.

Track changes to indexed method identities and member collections so provider reuse and lazy Populate callbacks retain existing behavior. Explicit-implementation renames do not invalidate the index because those methods are excluded; this also avoids rebuilding on the generator's own temporary renames. Tracking reuses an existing method-state bit. Weak type keys and member positions avoid retaining discarded types or removed methods, without allocating a weak reference for every method.

Performance

Baseline is 91b63bf88257142d4ffcb61d1728659ee0a51064; candidate is this change alone. Isolated and cumulative before/after/delta are identical for this independent PR: there are no prerequisite performance patches in either build. Both use the same source-built Release runtime; only the System.CodeDom implementation differs.

Windows 11 x64, Intel Core i7-14700; BenchmarkDotNet 0.16.0-preview.2. Each benchmark child verified its loaded DLL SHA256 and reported the source-built .NET 12.0.0 development runtime. The SDK/benchmark TFM is net11.0; that label is not the execution runtime. Each arm/case used one fresh process, 3 warmup iterations, 10 measured iterations and a 250 ms target iteration time. These are local measurements, not cross-machine confidence estimates or end-to-end compiler speedups.

FreshGraphAndGenerate includes graph construction, a new provider, generation and materializing the output string. + explicit adds one distinct explicit-interface implementation after each public method, doubling total method count. All public method names are unique; repeated expressions are not required for the optimization.

Case Before After Delta Change
FreshGraphAndGenerate, 1000 public 0.004 s 0.001 s (516.43 us) -0.004 s -88.49%
FreshGraphAndGenerate, 1000 public + explicit 0.008 s 0.001 s -0.006 s -81.59%
FreshGraphAndGenerate, 5000 public 0.100 s 0.005 s -0.095 s -95.46%
FreshGraphAndGenerate, 5000 public + explicit 0.308 s 0.025 s -0.282 s -91.75%

Managed allocation for those same operations:

Case Before After Delta Change
FreshGraphAndGenerate, 1000 public 1.844 MB 1.899 MB +0.054593 MB +2.96%
FreshGraphAndGenerate, 1000 public + explicit 4.398 MB 4.452 MB +0.054612 MB +1.24%
FreshGraphAndGenerate, 5000 public 9.354 MB 9.566 MB +0.212300 MB +2.27%
FreshGraphAndGenerate, 5000 public + explicit 22.355 MB 22.567 MB +0.212568 MB +0.95%

The full tables below include small graphs, unchanged provider reuse, rename invalidation, and graph construction alone. For large types, generation with a new provider allocates 2.33-8.37% more; reusing a provider allocates 2.64-7.36% less because indexed lookup also avoids a collection enumerator per method. Graph construction adds 8 bytes per graph in the direct allocation check; the method tracking bit adds no field. A new provider also adds 8 bytes in the small-type benchmarks.

Small-case mean times range from -9.43% to +7.93% in the main run; there is no claim of a uniform small-type speedup. The separate 32-public-method cutoff case is 5.43% slower, an observed increase of 0.72 us. All results, including increases, are retained below. The process-wide mutation epoch can conservatively rebuild unrelated indexes after an indexed graph changes. Name strings and dictionary capacity remain until rebuild or type collection.

Seconds are rounded by magnitude; sub-millisecond values also show microseconds so rounding does not hide small-case differences. MB/GB use decimal units. Deltas use unrounded values.

All 40 isolated and cumulative timing comparisons
Case Before After Delta Change
NewProvider, 1 public 0.000 s (0.34 us) 0.000 s (0.36 us) +0.000 s (+0.02 us) +7.06%
ReusedProvider, 1 public 0.000 s (0.32 us) 0.000 s (0.29 us) -0.000 s (-0.03 us) -8.09%
ReusedProviderAfterRename, 1 public 0.000 s (0.30 us) 0.000 s (0.29 us) -0.000 s (-0.01 us) -4.62%
FreshGraph, 1 public 0.000 s (0.09 us) 0.000 s (0.09 us) +0.000 s (+0.00 us) +1.71%
FreshGraphAndGenerate, 1 public 0.000 s (0.55 us) 0.000 s (0.56 us) +0.000 s (+0.01 us) +1.77%
NewProvider, 1 public + explicit 0.000 s (0.67 us) 0.000 s (0.60 us) -0.000 s (-0.06 us) -9.43%
ReusedProvider, 1 public + explicit 0.000 s (0.53 us) 0.000 s (0.56 us) +0.000 s (+0.03 us) +5.56%
ReusedProviderAfterRename, 1 public + explicit 0.000 s (0.54 us) 0.000 s (0.55 us) +0.000 s (+0.01 us) +2.13%
FreshGraph, 1 public + explicit 0.000 s (0.20 us) 0.000 s (0.19 us) -0.000 s (-0.01 us) -5.69%
FreshGraphAndGenerate, 1 public + explicit 0.000 s (0.99 us) 0.000 s (1.07 us) +0.000 s (+0.08 us) +7.93%
NewProvider, 10 public 0.000 s (2.16 us) 0.000 s (2.07 us) -0.000 s (-0.08 us) -3.83%
ReusedProvider, 10 public 0.000 s (2.06 us) 0.000 s (2.14 us) +0.000 s (+0.08 us) +3.78%
ReusedProviderAfterRename, 10 public 0.000 s (2.07 us) 0.000 s (1.98 us) -0.000 s (-0.09 us) -4.27%
FreshGraph, 10 public 0.000 s (0.76 us) 0.000 s (0.82 us) +0.000 s (+0.06 us) +7.79%
FreshGraphAndGenerate, 10 public 0.000 s (4.07 us) 0.000 s (3.76 us) -0.000 s (-0.31 us) -7.69%
NewProvider, 10 public + explicit 0.000 s (4.53 us) 0.000 s (4.80 us) +0.000 s (+0.27 us) +6.00%
ReusedProvider, 10 public + explicit 0.000 s (4.60 us) 0.000 s (4.62 us) +0.000 s (+0.02 us) +0.45%
ReusedProviderAfterRename, 10 public + explicit 0.000 s (4.82 us) 0.000 s (5.10 us) +0.000 s (+0.28 us) +5.78%
FreshGraph, 10 public + explicit 0.000 s (1.66 us) 0.000 s (1.68 us) +0.000 s (+0.01 us) +0.78%
FreshGraphAndGenerate, 10 public + explicit 0.000 s (8.16 us) 0.000 s (8.51 us) +0.000 s (+0.35 us) +4.25%
NewProvider, 1000 public 0.004 s 0.000 s (302.91 us) -0.004 s -92.35%
ReusedProvider, 1000 public 0.004 s 0.000 s (264.75 us) -0.004 s -93.53%
ReusedProviderAfterRename, 1000 public 0.004 s 0.000 s (262.47 us) -0.004 s -93.34%
FreshGraph, 1000 public 0.000 s (84.54 us) 0.000 s (83.76 us) -0.000 s (-0.78 us) -0.92%
FreshGraphAndGenerate, 1000 public 0.004 s 0.001 s (516.43 us) -0.004 s -88.49%
NewProvider, 1000 public + explicit 0.007 s 0.001 s (759.89 us) -0.006 s -89.23%
ReusedProvider, 1000 public + explicit 0.007 s 0.001 s (709.62 us) -0.006 s -89.78%
ReusedProviderAfterRename, 1000 public + explicit 0.007 s 0.001 s (745.10 us) -0.006 s -89.45%
FreshGraph, 1000 public + explicit 0.000 s (219.06 us) 0.000 s (217.69 us) -0.000 s (-1.37 us) -0.63%
FreshGraphAndGenerate, 1000 public + explicit 0.008 s 0.001 s -0.006 s -81.59%
NewProvider, 5000 public 0.088 s 0.003 s -0.084 s -96.29%
ReusedProvider, 5000 public 0.091 s 0.002 s -0.088 s -97.64%
ReusedProviderAfterRename, 5000 public 0.087 s 0.002 s -0.085 s -97.61%
FreshGraph, 5000 public 0.001 s (670.85 us) 0.001 s (614.52 us) -0.000 s (-56.33 us) -8.40%
FreshGraphAndGenerate, 5000 public 0.100 s 0.005 s -0.095 s -95.46%
NewProvider, 5000 public + explicit 0.292 s 0.005 s -0.287 s -98.19%
ReusedProvider, 5000 public + explicit 0.318 s 0.006 s -0.312 s -98.26%
ReusedProviderAfterRename, 5000 public + explicit 0.350 s 0.006 s -0.344 s -98.37%
FreshGraph, 5000 public + explicit 0.009 s 0.009 s +0.000 s (+177.55 us) +2.09%
FreshGraphAndGenerate, 5000 public + explicit 0.308 s 0.025 s -0.282 s -91.75%
All 40 isolated and cumulative allocation comparisons
Case Before After Delta Change
NewProvider, 1 public 0.001520 MB 0.001528 MB +0.000008 MB +0.53%
ReusedProvider, 1 public 0.001408 MB 0.001408 MB 0.000000 MB +0.00%
ReusedProviderAfterRename, 1 public 0.001400 MB 0.001400 MB 0.000000 MB +0.00%
FreshGraph, 1 public 0.001000 MB 0.001008 MB +0.000008 MB +0.80%
FreshGraphAndGenerate, 1 public 0.003288 MB 0.003304 MB +0.000016 MB +0.49%
NewProvider, 1 public + explicit 0.002720 MB 0.002728 MB +0.000008 MB +0.29%
ReusedProvider, 1 public + explicit 0.002608 MB 0.002608 MB 0.000000 MB +0.00%
ReusedProviderAfterRename, 1 public + explicit 0.002600 MB 0.002600 MB 0.000000 MB +0.00%
FreshGraph, 1 public + explicit 0.001816 MB 0.001824 MB +0.000008 MB +0.44%
FreshGraphAndGenerate, 1 public + explicit 0.005864 MB 0.005880 MB +0.000016 MB +0.27%
NewProvider, 10 public 0.007520 MB 0.007528 MB +0.000008 MB +0.11%
ReusedProvider, 10 public 0.007408 MB 0.007408 MB 0.000000 MB +0.00%
ReusedProviderAfterRename, 10 public 0.007408 MB 0.007408 MB 0.000000 MB +0.00%
FreshGraph, 10 public 0.007072 MB 0.007080 MB +0.000008 MB +0.11%
FreshGraphAndGenerate, 10 public 0.019897 MB 0.019913 MB +0.000016 MB +0.08%
NewProvider, 10 public + explicit 0.018360 MB 0.018368 MB +0.000008 MB +0.04%
ReusedProvider, 10 public + explicit 0.018248 MB 0.018248 MB 0.000000 MB +0.00%
ReusedProviderAfterRename, 10 public + explicit 0.018248 MB 0.018248 MB 0.000000 MB +0.00%
FreshGraph, 10 public + explicit 0.015512 MB 0.015520 MB +0.000008 MB +0.05%
FreshGraphAndGenerate, 10 public + explicit 0.044777 MB 0.044793 MB +0.000016 MB +0.04%
NewProvider, 1000 public 0.652386 MB 0.706970 MB +0.054584 MB +8.37%
ReusedProvider, 1000 public 0.652274 MB 0.604276 MB -0.047998 MB -7.36%
ReusedProviderAfterRename, 1000 public 0.652266 MB 0.604266 MB -0.048000 MB -7.36%
FreshGraph, 1000 public 0.687274 MB 0.687282 MB +0.000008 MB +0.00%
FreshGraphAndGenerate, 1000 public 1.844 MB 1.899 MB +0.054593 MB +2.96%
NewProvider, 1000 public + explicit 1.783 MB 1.838 MB +0.054607 MB +3.06%
ReusedProvider, 1000 public + explicit 1.783 MB 1.735 MB -0.047977 MB -2.69%
ReusedProviderAfterRename, 1000 public + explicit 1.783 MB 1.735 MB -0.047977 MB -2.69%
FreshGraph, 1000 public + explicit 1.550 MB 1.550 MB +0.000008 MB +0.00%
FreshGraphAndGenerate, 1000 public + explicit 4.398 MB 4.452 MB +0.054612 MB +1.24%
NewProvider, 5000 public 3.279 MB 3.491 MB +0.212012 MB +6.46%
ReusedProvider, 5000 public 3.279 MB 3.040 MB -0.239676 MB -7.31%
ReusedProviderAfterRename, 5000 public 3.279 MB 3.040 MB -0.239676 MB -7.31%
FreshGraph, 5000 public 3.554 MB 3.554 MB +0.000008 MB +0.00%
FreshGraphAndGenerate, 5000 public 9.354 MB 9.566 MB +0.212300 MB +2.27%
NewProvider, 5000 public + explicit 9.079 MB 9.291 MB +0.211940 MB +2.33%
ReusedProvider, 5000 public + explicit 9.079 MB 8.839 MB -0.239782 MB -2.64%
ReusedProviderAfterRename, 5000 public + explicit 9.079 MB 8.839 MB -0.239844 MB -2.64%
FreshGraph, 5000 public + explicit 7.956 MB 7.956 MB +0.000009 MB +0.00%
FreshGraphAndGenerate, 5000 public + explicit 22.355 MB 22.567 MB +0.212568 MB +0.95%
Separate cutoff check: 16, 32 and 64 public methods

These 12 jobs used the same final binaries and settings. They are a separate run, not pooled with the main matrix. The cutoff counts all members, including explicit implementations.

Case Before After Delta Change
FreshGraphAndGenerate, 16 public 0.000 s (6.10 us) 0.000 s (6.04 us) -0.000 s (-0.05 us) -0.83%
FreshGraphAndGenerate, 16 public + explicit 0.000 s (13.35 us) 0.000 s (13.22 us) -0.000 s (-0.13 us) -0.97%
FreshGraphAndGenerate, 32 public 0.000 s (13.23 us) 0.000 s (13.95 us) +0.000 s (+0.72 us) +5.43%
FreshGraphAndGenerate, 32 public + explicit 0.000 s (31.96 us) 0.000 s (24.61 us) -0.000 s (-7.35 us) -23.00%
FreshGraphAndGenerate, 64 public 0.000 s (36.55 us) 0.000 s (20.88 us) -0.000 s (-15.67 us) -42.86%
FreshGraphAndGenerate, 64 public + explicit 0.000 s (73.84 us) 0.000 s (52.65 us) -0.000 s (-21.19 us) -28.70%
Case Before After Delta Change
FreshGraphAndGenerate, 16 public 0.031617 MB 0.031633 MB +0.000016 MB +0.05%
FreshGraphAndGenerate, 16 public + explicit 0.072122 MB 0.072138 MB +0.000016 MB +0.02%
FreshGraphAndGenerate, 32 public 0.061666 MB 0.061682 MB +0.000016 MB +0.03%
FreshGraphAndGenerate, 32 public + explicit 0.142716 MB 0.143636 MB +0.000920 MB +0.64%
FreshGraphAndGenerate, 64 public 0.121667 MB 0.123595 MB +0.001928 MB +1.58%
FreshGraphAndGenerate, 64 public + explicit 0.283424 MB 0.285353 MB +0.001929 MB +0.68%

Validation

  • Official baseline: build.cmd clr+libs -rc Release -lc Release /m:1 /nr:false /p:UseSharedCompilation=false /p:ImportDirectoryPackagesProps=false passed. It reported 3 existing NU1902 package warnings.
  • Final normal four-target library build passed API compatibility and analyzers: net11.0, net10.0, netstandard2.0 and net462; 0 warnings/errors. No ref API changes.
  • Final full CodeDOM suites: 6,014 passed on the current-runtime target; 3,217 passed on net481; no failures/skips or build/analyzer warnings. The framework target is compatibility coverage, not evidence that it executes the changed modern-runtime DLL. The earlier baseline suites passed 6,007/3,210 tests before the final additional cases were added.
  • 32 generated-text SHA256 comparisons and 8 graph-member-count comparisons match the baseline. Tests cover case-insensitive/null names, repeated references, overload flags, private/public transitions, IList mutations, Populate callbacks, shared members, nested types, provider reuse, cutoff transitions and collection lifetime.
  • Final test command: .dotnet/dotnet.exe build src/libraries/System.CodeDom/tests/System.CodeDom.Tests.csproj -c Release /t:Test /m:1 /nr:false /p:UseSharedCompilation=false /p:ImportDirectoryPackagesProps=false /p:RuntimeConfiguration=Release /p:RunAnalyzersInBuild=true.

Reproduce the measurements

Build the baseline runtime/testhost in Release, preserve it, then build this library change in Release and copy the exact implementation DLL beside the candidate corerun. Keep both runtime directories otherwise identical. This is an out-of-shared-framework library, so the implementation DLL must be placed beside each corerun; the benchmark rejects any other loaded DLL hash.

Create the following project in a fresh directory outside the runtime checkout. Put the baseline implementation at reference/System.CodeDom.dll, fill in plan.json, set CODEDOM_BENCH_PLAN to its absolute path, and run dotnet run -c Release -- --filter '*'. The benchmark exports full JSON statistics including confidence intervals and managed allocations. For the cutoff run replace both 1, 10, 1000, 5000 lists with 16, 32, 64 and filter *FreshGraphAndGenerate*. The --verify mode is output verification only; its un-warmed timings are not used in these performance tables.

Benchmark.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
    <Optimize>true</Optimize>
    <UseSharedCompilation>false</UseSharedCompilation>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BenchmarkDotNet" Version="0.16.0-preview.2" />
    <Reference Include="System.CodeDom">
      <HintPath>reference/System.CodeDom.dll</HintPath>
      <Private>true</Private>
    </Reference>
  </ItemGroup>
</Project>
plan.json template
{
  "readyForBenchmarks": true,
  "dotnet": "<absolute path to the repository SDK dotnet.exe>",
  "hosts": [
    {
      "name": "Baseline",
      "coreRun": "<absolute path to baseline corerun.exe>",
      "codeDomSha256": "<SHA256 of baseline System.CodeDom.dll>"
    },
    {
      "name": "Candidate",
      "coreRun": "<absolute path to candidate corerun.exe>",
      "codeDomSha256": "<SHA256 of candidate System.CodeDom.dll>"
    }
  ]
}
Program.cs — exact main-matrix harness
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Exporters.Json;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Toolchains.CoreRun;
using Perfolizer.Horology;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.IO;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Microsoft.VisualBasic;

if (args.Length == 1 && args[0] == "--verify")
{
    foreach (int count in new[] { 1, 10, 1000, 5000 })
    foreach (bool interleaved in new[] { false, true })
    foreach (string method in new[] { "NewProvider", "ReusedProvider", "ReusedProviderAfterRename", "FreshGraph", "FreshGraphAndGenerate" })
    {
        var benchmark = new VisualBasicGeneration { MethodCount = count, InterleaveExplicitImplementations = interleaved };
        benchmark.Setup();
        long before = GC.GetAllocatedBytesForCurrentThread();
        long start = Stopwatch.GetTimestamp();
        object output = method switch
        {
            "NewProvider" => benchmark.NewProvider(),
            "ReusedProvider" => benchmark.ReusedProvider(),
            "ReusedProviderAfterRename" => benchmark.ReusedProviderAfterRename(),
            "FreshGraph" => benchmark.FreshGraph(),
            "FreshGraphAndGenerate" => benchmark.FreshGraphAndGenerate(),
            _ => throw new InvalidOperationException()
        };
        double seconds = Stopwatch.GetElapsedTime(start).TotalSeconds;
        long allocated = GC.GetAllocatedBytesForCurrentThread() - before;
        string? text = output as string;
        Console.WriteLine(JsonSerializer.Serialize(new
        {
            kind = "verification", method, count, interleaved, seconds, allocated,
            characters = text?.Length,
            sha256 = text is null ? null : Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(text))),
            members = (output as CodeTypeDeclaration)?.Members.Count
        }));
        benchmark.Cleanup();
    }
    return;
}

string planFile = Environment.GetEnvironmentVariable("CODEDOM_BENCH_PLAN")
    ?? throw new InvalidOperationException("CODEDOM_BENCH_PLAN must identify the frozen host manifest.");
using JsonDocument plan = JsonDocument.Parse(File.ReadAllText(planFile));
if (!plan.RootElement.GetProperty("readyForBenchmarks").GetBoolean())
    throw new InvalidOperationException("Baseline and candidate hosts are not ready for comparison.");
var configuration = ManualConfig.Create(DefaultConfig.Instance).AddExporter(JsonExporter.Full)
    .WithOptions(ConfigOptions.DisableParallelBuild | ConfigOptions.StopOnFirstError);
foreach (JsonElement host in plan.RootElement.GetProperty("hosts").EnumerateArray())
{
    string name = host.GetProperty("name").GetString()!;
    var settings = new CoreRunSettings
    {
        SourceCoreRun = new FileInfo(host.GetProperty("coreRun").GetString()!),
        TargetFrameworkMoniker = "net11.0",
        CliPath = new FileInfo(plan.RootElement.GetProperty("dotnet").GetString()!),
        DisplayName = name,
        CreateCopy = true
    };
    Job job = Job.Default.WithId(name).WithToolchain(CoreRunToolchain.From(settings))
        .WithWarmupCount(3).WithIterationCount(10).WithLaunchCount(1)
        .WithIterationTime(TimeInterval.FromMilliseconds(250))
        .WithEnvironmentVariable("CODEDOM_EXPECTED_SHA256", host.GetProperty("codeDomSha256").GetString()!);
    if (name == "Baseline")
        job = job.AsBaseline();
    configuration.AddJob(job);
}
BenchmarkSwitcher.FromAssembly(typeof(VisualBasicGeneration).Assembly).Run(args, configuration);


[MemoryDiagnoser]
public class VisualBasicGeneration
{
    private readonly CodeGeneratorOptions _options = new() { BlankLinesBetweenMembers = false, VerbatimOrder = true };
    private readonly VBCodeProvider _provider = new();
    private CodeTypeDeclaration _type = new("Example");
    private bool _alternateName;

    [Params(1, 10, 1000, 5000)]
    public int MethodCount { get; set; }

    [Params(false, true)]
    public bool InterleaveExplicitImplementations { get; set; }

    [GlobalSetup]
    public void Setup()
    {
        Assembly assembly = typeof(CodeTypeDeclaration).Assembly;
        string expected = Environment.GetEnvironmentVariable("CODEDOM_EXPECTED_SHA256")
            ?? throw new InvalidOperationException("Missing expected CodeDOM hash.");
        string actual = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(assembly.Location)));
        if (!string.Equals(expected, actual, StringComparison.OrdinalIgnoreCase))
            throw new InvalidOperationException($"Incorrect CodeDOM assembly: {assembly.Location}, {actual}");
        Console.WriteLine(JsonSerializer.Serialize(new { kind = "binding", path = assembly.Location, sha256 = actual, runtime = Environment.Version.ToString() }));
        _type = CreateType();
    }

    private CodeTypeDeclaration CreateType()
    {
        var type = new CodeTypeDeclaration("Example");
        for (int index = 0; index < MethodCount; index++)
        {
            var method = new CodeMemberMethod
            {
                Name = "Method" + index.ToString(CultureInfo.InvariantCulture),
                Attributes = MemberAttributes.Public | MemberAttributes.Final,
                ReturnType = new CodeTypeReference(typeof(int))
            };
            method.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(index)));
            type.Members.Add(method);
            if (InterleaveExplicitImplementations)
            {
                var implementation = new CodeMemberMethod
                {
                    Name = "Explicit" + index.ToString(CultureInfo.InvariantCulture),
                    PrivateImplementationType = new CodeTypeReference("IExample"),
                    ReturnType = new CodeTypeReference(typeof(int))
                };
                implementation.Statements.Add(new CodeMethodReturnStatement(new CodePrimitiveExpression(index)));
                type.Members.Add(implementation);
            }
        }
        return type;
    }

    [GlobalCleanup]
    public void Cleanup() => _provider.Dispose();

    [Benchmark]
    public string NewProvider()
    {
        using var provider = new VBCodeProvider();
        return Generate(provider, _type);
    }

    [Benchmark]
    public string ReusedProvider() => Generate(_provider, _type);

    [Benchmark]
    public string ReusedProviderAfterRename()
    {
        _alternateName = !_alternateName;
        int lastPublicIndex = (MethodCount - 1) * (InterleaveExplicitImplementations ? 2 : 1);
        _type.Members[lastPublicIndex].Name = _alternateName ? "LastA" : "LastB";
        return Generate(_provider, _type);
    }

    [Benchmark]
    public object FreshGraph() => CreateType();

    [Benchmark]
    public string FreshGraphAndGenerate()
    {
        CodeTypeDeclaration type = CreateType();
        using var provider = new VBCodeProvider();
        return Generate(provider, type);
    }

    private string Generate(VBCodeProvider provider, CodeTypeDeclaration type)
    {
        using var writer = new StringWriter(CultureInfo.InvariantCulture);
        provider.GenerateCodeFromType(type, writer, _options);
        return writer.ToString();
    }
}

Note

This contribution was prepared with AI assistance.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 19, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.CodeDom community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants