Skip to content

Skip unnecessary literal scans on .NET Framework - #2283

Open
tuncaypeker wants to merge 1 commit into
DapperLib:mainfrom
tuncaypeker:perf/legacy-literal-token-scan
Open

tuncaypeker wants to merge 1 commit into
DapperLib:mainfrom
tuncaypeker:perf/legacy-literal-token-scan

Conversation

@tuncaypeker

Copy link
Copy Markdown
Contributor

Related to #1484.

GetLiteralTokens runs the .NET Framework compiled regex over every command, even when it cannot contain a literal token. Use IndexOf('{') to reject brace-free commands and pass the first brace's index to both regex calls, avoiding another scan over the same prefix when tokens are present. The regex still enforces the existing token syntax, Unicode rules, and preceding-character boundary.

This optimization is limited to the .NET Framework build. The netstandard2.0 and modern .NET implementations keep their existing parsing path. No public API, settings, or dependencies are added.

Validation:

  • Added 25 database-free cases for empty/null commands, ordinary parameters, malformed tokens, Unicode member names and boundaries, duplicate tokens, case-distinct members, invalid first braces followed by valid tokens, and tokens at the end of long commands.
  • SQL Server integration tests use SQL Server 2025 LocalDB with both Microsoft.Data.SqlClient and System.Data.SqlClient.
  • New parsing cases plus existing LiteralTests, ParameterTests, and SQLite tests pass on net481 (188 passed / 7 skipped), net8.0 (183 passed / 4 skipped), and net10.0 (183 passed / 4 skipped), with no failures. The 25 new cases pass on every target. Skips are existing disabled list-padding/performance and provider-specific spatial tests.
  • The full repository test suite was not run.
  • Release library build succeeds for net461, netstandard2.0, net8.0, and net10.0 with zero warnings or errors.

Benchmark:
BenchmarkDotNet 0.15.8, net481 executable, .NET Framework host 4.8.10008.0, x64 RyuJIT, Intel Core i7-1360P, Windows 11. InProcessEmit toolchain, one launch, three warmups, ten measured iterations of 250 ms. The unchanged upstream parser and candidate Release parser are loaded into separate assembly contexts in the same process and invoked through equivalent cached delegates. A setup check rejects accidental assembly unification. These are synthetic parser microbenchmarks with 10,000 characters of padding, not end-to-end database timings.

SQL shape Before mean (us) After mean (us)
No opening brace 52.524 7.954
Non-token brace at end 48.929 4.254
Malformed token at end 46.743 6.516
Valid token at end 95.251 5.000
Valid token near start 53.856 47.150

The early-token measurements have overlapping error intervals (before +/-13.639 us, after +/-16.179 us); no speedup is claimed for that case. The primary benefit is avoiding the .NET Framework regex's character-by-character scan over a long prefix. Modern .NET and netstandard2.0 retain their original code path.

Standalone benchmark reproduction

Build and save separate net461 Release DLLs before and after the change. Set DAPPER_BENCH_BASELINE and DAPPER_BENCH_CANDIDATE to their absolute paths. Create the following bench.csproj and Program.cs outside the repository, build in Release, and run the resulting net481 executable with --filter '*'. This harness needs no database.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net481</TargetFramework><LangVersion>latest</LangVersion></PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BenchmarkDotNet" Version="0.15.8" />
    <PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="10.0.8" />
  </ItemGroup>
</Project>
using System;
using System.Reflection;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Toolchains.InProcess.Emit;
using Perfolizer.Horology;


public class Program
{
    public static void Main(string[] args)
    {
        var job = Job.ShortRun.WithToolchain(InProcessEmitToolchain.Instance)
            .WithWarmupCount(3).WithIterationCount(10).WithIterationTime(TimeInterval.FromMilliseconds(250));
        BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, DefaultConfig.Instance.AddJob(job));
    }
}

[MemoryDiagnoser]
public class LiteralScan
{
    private Func<string, object> before, after;
    private string sql;

    [Params(10000)]
    public int Length { get; set; }

    [Params("Absent", "Present", "EarlyToken", "Malformed", "BraceOnly")]
    public string Shape { get; set; }

    [GlobalSetup]
    public void Setup()
    {
        before = Load(Environment.GetEnvironmentVariable("DAPPER_BENCH_BASELINE"));
        after = Load(Environment.GetEnvironmentVariable("DAPPER_BENCH_CANDIDATE"));
        if (before.Method == after.Method) throw new InvalidOperationException("Benchmark assemblies were unified");
        string suffix = Shape == "Present" ? " {=Value}" : Shape == "Malformed" ? " {=}" : Shape == "BraceOnly" ? " {x}" : "";
        sql = (Shape == "EarlyToken" ? "select {=Value} /* " : "select @Id /* ") + new string('a', Length) + " */" + suffix;
    }

    private static Func<string, object> Load(string path)
    {
        var assembly = Assembly.LoadFile(path);
        var method = assembly.GetType("Dapper.SqlMapper").GetMethod("GetLiteralTokens", BindingFlags.NonPublic | BindingFlags.Static);
        return (Func<string, object>)Delegate.CreateDelegate(typeof(Func<string, object>), method);
    }

    [Benchmark(Baseline = true)]
    public object Before() => before(sql);
    [Benchmark]
    public object After() => after(sql);
}

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant