diff --git a/.gitignore b/.gitignore index 940794e..a60b2b6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## +BenchmarkDotNet.Artifacts/ + ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files diff --git a/CHANGELOG.md b/CHANGELOG.md index bddbf8c..3457a34 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## v6.0.3 + +- Accelerated `PartialRatio` prefix and suffix scoring with incremental bit-parallel LCS rows while preserving full-window search and alignment tie ordering. +- Reused single-word pattern masks for reversed suffix scans, removing the extra pattern-vector allocation for inputs up to 64 elements. +- Combined multiword partial-ratio mask presence checks and retrieval into one lookup, avoiding duplicate dictionary searches for generic and non-ASCII inputs. +- Simplified multiword LCS updates by eliminating unnecessary borrow propagation in similarity and matrix calculations. +- Reduced built-in `TokenSetRatio` and cached scorer work with exact prefix-length scores and an early return for nonempty token subsets; custom scorer behavior is preserved. +- Added exhaustive dynamic-programming checks for long partial-ratio windows, edge alignments, word boundaries, and short-input allocations. + ## v6.0.2 - Reduced parallel extraction allocations by using indexed choices directly and pooling top-N score buffers. diff --git a/FuzzySharp.Benchmarks/Compare-Performance.ps1 b/FuzzySharp.Benchmarks/Compare-Performance.ps1 new file mode 100644 index 0000000..832803d --- /dev/null +++ b/FuzzySharp.Benchmarks/Compare-Performance.ps1 @@ -0,0 +1,64 @@ +param( + [string] $BaselineRef = 'origin/master', + [string] $Filter = '*RegressionBenchmarks*', + [int] $IterationCount = 5, + [int] $IterationTimeMs = 150 +) + +$ErrorActionPreference = 'Stop' +$repoRoot = Split-Path -Parent $PSScriptRoot +$baselineCommit = & git -C $repoRoot rev-parse --verify "$BaselineRef^{commit}" +if ($LASTEXITCODE -ne 0) { throw "Cannot resolve baseline $BaselineRef" } +$runName = '{0}-{1}-{2}' -f (Get-Date -Format 'yyyyMMdd-HHmmss'), $baselineCommit.Substring(0, 12), [guid]::NewGuid().ToString('N').Substring(0, 8) +$runRoot = Join-Path $repoRoot "artifacts/performance/$runName" +$baselineRoot = Join-Path $runRoot 'baseline' +New-Item -ItemType Directory -Path $baselineRoot -Force | Out-Null +$archivePath = Join-Path $runRoot 'baseline.tar' +& git -C $repoRoot archive $baselineCommit FuzzySharp build Directory.Build.props README.md "--output=$archivePath" +if ($LASTEXITCODE -ne 0) { throw 'git archive failed' } +& tar -xf $archivePath -C $baselineRoot +if ($LASTEXITCODE -ne 0) { throw 'Baseline extraction failed' } +& dotnet build (Join-Path $baselineRoot 'FuzzySharp/FuzzySharp.csproj') -c Release -f NET10.0 -p:AssemblyName=FuzzySharp.PerformanceBaseline -p:GeneratePackageOnBuild=false -v minimal +if ($LASTEXITCODE -ne 0) { throw 'Baseline build failed' } + +@( + "Baseline ref: $BaselineRef", + "Baseline commit: $baselineCommit", + "Candidate commit: $(& git -C $repoRoot rev-parse HEAD)", + 'Candidate diff (includes local edits):', + (& git -C $repoRoot diff --stat), + "Filter: $Filter", + "Iterations: $IterationCount; iteration time: $IterationTimeMs ms" +) | Set-Content -LiteralPath (Join-Path $runRoot 'run.txt') -Encoding utf8 +$patchPath = Join-Path $runRoot 'candidate.patch' +& git -C $repoRoot diff "--output=$patchPath" +if ($LASTEXITCODE -ne 0) { throw 'Cannot record candidate diff' } + +# Environment properties are inherited by BenchmarkDotNet's generated build. +$previousBaseline = $env:FuzzySharpPerformanceBaseline +try { + $env:FuzzySharpPerformanceBaseline = Join-Path $baselineRoot 'FuzzySharp/bin/Release/net10.0/FuzzySharp.PerformanceBaseline.dll' + Push-Location $repoRoot + try { + # Rebuild also refreshes deps.json when switching the optional baseline. + & dotnet build (Join-Path $PSScriptRoot 'FuzzySharp.Benchmarks.csproj') -c Release -t:Rebuild -p:GeneratePackageOnBuild=false -v minimal + if ($LASTEXITCODE -ne 0) { throw 'Candidate build failed' } + & dotnet run --project (Join-Path $PSScriptRoot 'FuzzySharp.Benchmarks.csproj') -c Release --no-build -- --filter $Filter --iterationCount $IterationCount --iterationTime $IterationTimeMs --warmupCount 3 --launchCount 1 --artifacts (Join-Path $runRoot 'results') + if ($LASTEXITCODE -ne 0) { throw 'Benchmark process failed' } + } + finally { Pop-Location } + + $resultFiles = @(Get-ChildItem (Join-Path $runRoot 'results/results') -Filter '*-report.csv') + if ($resultFiles.Count -eq 0) { throw 'No benchmark results produced' } + foreach ($resultFile in $resultFiles) { + $rows = @(Import-Csv -LiteralPath $resultFile.FullName) + if ($rows.Count -eq 0 -or @($rows | Where-Object { $_.Mean -notmatch '\d' }).Count -ne 0) { + throw "Missing measurements in $($resultFile.FullName)" + } + if (@($rows | Where-Object Method -eq 'Before').Count -eq 0) { + throw "Baseline missing from $($resultFile.FullName)" + } + } +} +finally { $env:FuzzySharpPerformanceBaseline = $previousBaseline } +Write-Host "Performance results: $runRoot" diff --git a/FuzzySharp.Benchmarks/FuzzySharp.Benchmarks.csproj b/FuzzySharp.Benchmarks/FuzzySharp.Benchmarks.csproj index 5710683..4ba91d6 100644 --- a/FuzzySharp.Benchmarks/FuzzySharp.Benchmarks.csproj +++ b/FuzzySharp.Benchmarks/FuzzySharp.Benchmarks.csproj @@ -20,6 +20,18 @@ + + + $(DefineConstants);FUZZYSHARP_PERFORMANCE_BASELINE + + + + $(FuzzySharpPerformanceBaseline) + baseline + + + diff --git a/FuzzySharp.Benchmarks/PartialRatioMultiwordBenchmarks.cs b/FuzzySharp.Benchmarks/PartialRatioMultiwordBenchmarks.cs new file mode 100644 index 0000000..f92b272 --- /dev/null +++ b/FuzzySharp.Benchmarks/PartialRatioMultiwordBenchmarks.cs @@ -0,0 +1,34 @@ +using BenchmarkDotNet.Attributes; +using Classic = FuzzySharp; + +namespace Raffinert.FuzzySharp.Benchmarks; + +[MemoryDiagnoser] +public class PartialRatioMultiwordBenchmarks +{ + [Params(65, 257, 1025)] + public int Length { get; set; } + + [Params("ASCII", "Cyrillic")] + public string Alphabet { get; set; } = "ASCII"; + + private string _first = ""; + private string _second = ""; + + [GlobalSetup] + public void Setup() + { + var random = new Random(Length * 7919); + int start = Alphabet == "Cyrillic" ? 0x400 : 'a'; + _first = new string(Enumerable.Range(0, Length) + .Select(_ => (char)(start + random.Next(16))).ToArray()); + _second = new string(Enumerable.Range(0, Length) + .Select(_ => (char)(start + random.Next(16))).ToArray()); + } + + [Benchmark] + public double PartialRatio() => Fuzz.PartialRatio(_first, _second); + + [Benchmark(Baseline = true)] + public double PartialRatioClassic() => Classic.Fuzz.PartialRatio(_first, _second); +} diff --git a/FuzzySharp.Benchmarks/PerformanceRegressionBenchmarks.cs b/FuzzySharp.Benchmarks/PerformanceRegressionBenchmarks.cs new file mode 100644 index 0000000..2305a3b --- /dev/null +++ b/FuzzySharp.Benchmarks/PerformanceRegressionBenchmarks.cs @@ -0,0 +1,154 @@ +#if FUZZYSHARP_PERFORMANCE_BASELINE +extern alias baseline; +using Baseline = baseline::Raffinert.FuzzySharp; +#endif +using BenchmarkDotNet.Attributes; +using Raffinert.FuzzySharp.SimilarityRatio.Scorer.StrategySensitive; + +namespace Raffinert.FuzzySharp.Benchmarks; + +[MemoryDiagnoser] +public class PartialRatioRegressionBenchmarks +{ + [Params("short-real", "same-7", "same-64", "equal-7", "equal-8", "equal-9", "equal-16", + "equal-64", "equal-65", "equal-257", "edge-65", "edge-1025", "long-65", "exact-65", + "absent-7", "absent-65", "absent-1024", "unicode-7", "unicode-65")] + public string Scenario { get; set; } = ""; + + private string _first = "", _second = ""; + + [GlobalSetup] + public void Setup() + { + if (Scenario == "short-real") + { + (_first, _second) = ("similar", "somewhresimlrbetweenthisstring"); + return; + } + + int length = int.Parse(Scenario.Split('-')[1]); + string alphabet = Scenario.StartsWith("unicode") ? "абвгґдеє" : "abcdefgh"; + _first = RegressionBenchmarkData.RandomText(length, length, alphabet); + _second = Scenario.Split('-')[0] switch + { + "same" => _first, + "equal" or "unicode" => RegressionBenchmarkData.RandomText(length, length + 17, alphabet), + "exact" => "zz" + _first + "zz", + "long" => RegressionBenchmarkData.RandomText(512, 71) + RegressionBenchmarkData.RandomText(length, 72) + + RegressionBenchmarkData.RandomText(512, 73), + "absent" => new string('z', length), + _ => RegressionBenchmarkData.RandomText(length + 17, length + 17) + }; + if (Scenario.StartsWith("absent")) + _first = new string('a', length); + } + + [Benchmark] public double Latest() => Fuzz.PartialRatio(_first, _second); +#if FUZZYSHARP_PERFORMANCE_BASELINE + [Benchmark(Baseline = true)] public double Before() => Baseline.Fuzz.PartialRatio(_first, _second); +#endif +} + +[MemoryDiagnoser] +public class TokenSetRegressionBenchmarks +{ + [Params("small", "subset", "disjoint", "long-overlap")] + public string Scenario { get; set; } = ""; + private string _first = "", _second = ""; + + [GlobalSetup] public void Setup() => (_first, _second) = RegressionBenchmarkData.Tokens(Scenario); + [Benchmark] public double Latest() => Fuzz.TokenSetRatio(_first, _second); +#if FUZZYSHARP_PERFORMANCE_BASELINE + [Benchmark(Baseline = true)] public double Before() => Baseline.Fuzz.TokenSetRatio(_first, _second); +#endif +} + +[MemoryDiagnoser] +public class CachedTokenSetRegressionBenchmarks +{ + [Params("small", "subset", "disjoint", "long-overlap")] + public string Scenario { get; set; } = ""; + private string _second = ""; + private CachedTokenSetScorer _latest = null!; +#if FUZZYSHARP_PERFORMANCE_BASELINE + private Baseline.SimilarityRatio.Scorer.StrategySensitive.CachedTokenSetScorer _before = null!; +#endif + + [GlobalSetup] + public void Setup() + { + var (first, second) = RegressionBenchmarkData.Tokens(Scenario); + _second = second; + _latest = new CachedTokenSetScorer(first); +#if FUZZYSHARP_PERFORMANCE_BASELINE + _before = new Baseline.SimilarityRatio.Scorer.StrategySensitive.CachedTokenSetScorer(first); +#endif + } + + [GlobalCleanup] + public void Cleanup() + { + _latest.Dispose(); +#if FUZZYSHARP_PERFORMANCE_BASELINE + _before.Dispose(); +#endif + } + + [Benchmark] public double Latest() => _latest.Score(_second); +#if FUZZYSHARP_PERFORMANCE_BASELINE + [Benchmark(Baseline = true)] public double Before() => _before.Score(_second); +#endif +} + +[MemoryDiagnoser] +public class LcsRegressionBenchmarks +{ + [Params(65, 257, 1025)] public int Length { get; set; } + private string _first = "", _second = ""; + [GlobalSetup] public void Setup() + { + _first = RegressionBenchmarkData.RandomText(Length, 41); + _second = RegressionBenchmarkData.RandomText(Length + 17, 43); + } + [Benchmark] public int Latest() => LongestCommonSubsequence.Similarity(_first, _second); +#if FUZZYSHARP_PERFORMANCE_BASELINE + [Benchmark(Baseline = true)] public int Before() => Baseline.LongestCommonSubsequence.Similarity(_first, _second); +#endif +} + +[MemoryDiagnoser] +public class MatrixRegressionBenchmarks +{ + [Params(129, 1025)] public int Length { get; set; } + private string _first = "", _second = ""; + [GlobalSetup] public void Setup() + { + _first = RegressionBenchmarkData.RandomText(Length, 41); + _second = RegressionBenchmarkData.RandomText(Length + 17, 43); + } + [Benchmark] public int Latest() => LongestCommonSubsequence.Matrix(_first, _second).Sim; +#if FUZZYSHARP_PERFORMANCE_BASELINE + [Benchmark(Baseline = true)] public int Before() => Baseline.LongestCommonSubsequence.Matrix(_first, _second).Sim; +#endif +} + +internal static class RegressionBenchmarkData +{ + internal static string RandomText(int length, int seed, string alphabet = "abcdefgh") + { + var random = new Random(seed); + var chars = new char[length]; + for (int i = 0; i < chars.Length; i++) + chars[i] = alphabet[random.Next(alphabet.Length)]; + return new string(chars); + } + + internal static (string First, string Second) Tokens(string scenario) => scenario switch + { + "small" => ("fuzzy was a bear", "fuzzy fuzzy fuzzy bear"), + "subset" => ("apple banana", "apple banana orange"), + "disjoint" => ("apple banana cherry", "kiwi lemon pear"), + _ => (string.Join(' ', Enumerable.Range(0, 32).Select(i => $"token{i:D3}")), + string.Join(' ', Enumerable.Range(16, 32).Select(i => $"token{i:D3}"))) + }; +} diff --git a/FuzzySharp.Benchmarks/README.md b/FuzzySharp.Benchmarks/README.md index 7a099d7..8c483da 100644 --- a/FuzzySharp.Benchmarks/README.md +++ b/FuzzySharp.Benchmarks/README.md @@ -1,75 +1,130 @@ # Benchmarks -## Latest library versus Classic +## Measured build versus Classic -Measured on 2026-11-24. **Latest** is the project reference to Raffinert.FuzzySharp **6.0.2** at commit `aab9111`; **Classic** is the `FuzzySharp` **2.0.2** NuGet package referenced by this benchmark project. Each row compares the corresponding methods on the same benchmark input. The speedup column is `Classic mean / latest mean`, so values above 1 mean the latest library was faster in this run. +Measured on **2026-11-28**. **Measured build** is a development build of Raffinert.FuzzySharp including the single mask lookup in multiword partial-ratio edge scans. **Classic** is the original [FuzzySharp](https://github.com/JakeBayer/FuzzySharp) **2.0.2** NuGet package. Every pair uses the same benchmark input. Speedup is `Classic mean / measured mean`. -BenchmarkDotNet 0.15.8 ran the `ShortRun` job in isolated processes: one launch, three warmup iterations and three measured iterations, with `MemoryDiagnoser`. Host: Windows 11 (10.0.26300.9974), Intel Core Ultra 9 275HX, 24 logical cores, .NET SDK 10.0.403 and .NET 10.0.14 x64 RyuJIT. +The measured library sources are at [e60e993](https://github.com/Raffinert/FuzzySharp/commit/e60e99337b6ae3d05153a66ce41dbed68598e470). This snapshot precedes the subsequent token-set scorer refactor; its numbers do not measure that refactor. Use the linked revision's sources with the commands below to reproduce this snapshot. + +BenchmarkDotNet 0.15.8 ran the workloads in isolated processes with `MemoryDiagnoser`: two launches, six warmups and ten measured iterations per launch, 300 ms target iteration time, and no outlier removal. Host: Windows 11 (10.0.26300.9974), Intel Core Ultra 9 275HX, 24 physical/logical cores, .NET SDK 11.0.100, .NET 10.0.15 x64 RyuJIT. Sequential methods run on logical CPU 10, a P-core (affinity mask `1024`); parallel extraction methods use P-cores 10–13 (mask `15360`). Core classes were checked through [Windows CPU Set Information](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-system_cpu_set_information). `DOTNET_TieredCompilation=0` disables JIT tier transitions and dynamic PGO, selecting optimized code from startup. This is an explicitly controlled JIT configuration rather than the runtime default. A five-second idle probe before calibration reported 1.7% total CPU use; temperature was not recorded. + +These tables replace the earlier unrestricted-affinity run, which showed large variation in unchanged methods. The JIT and affinity settings differ from that run, so absolute times across the two runs do not establish a code regression. All pairs below use the same configuration; `±` denotes BenchmarkDotNet's 99.9% confidence-interval half-width. ### Scoring -Times are mean nanoseconds per operation; allocations are bytes per operation. +Times are mean nanoseconds per operation with 99.9% confidence intervals. Allocations use the units reported by BenchmarkDotNet. -| Operation | Latest | Classic | Speedup | Allocated: latest | Allocated: Classic | +| Operation | Measured build | Classic 2.0.2 | Speedup | Allocated: measured | Allocated: Classic | | --- | ---: | ---: | ---: | ---: | ---: | -| `Ratio` | 55.20 ns | 124.60 ns | 2.26× | 80 B | 320 B | -| `PartialRatio` | 239.98 ns | 536.44 ns | 2.24× | 256 B | 3,368 B | -| `PartialRatio` (short pattern in 517-character text) | 1,132.50 ns | 10,083.48 ns | 8.90× | 1,016 B | 59,201 B | -| `WeightedRatio` | 2,273.55 ns | 6,312.93 ns | 2.78× | 3,776 B | 11,809 B | -| `TokenSortRatio` | 307.50 ns | 727.27 ns | 2.37× | 648 B | 2,024 B | -| `TokenSetRatio` | 337.43 ns | 1,143.08 ns | 3.39× | 1,496 B | 4,096 B | -| `PartialTokenSortRatio` | 562.95 ns | 808.24 ns | 1.44× | 648 B | 2,344 B | -| `PartialTokenSetRatio` | 592.46 ns | 1,362.45 ns | 2.30× | 1,848 B | 5,584 B | -| `TokenAbbreviationRatio` | 314.88 ns | 663.63 ns | 2.11× | 1,680 B | 2,984 B | -| `PartialTokenAbbreviationRatio` | 375.46 ns | 838.65 ns | 2.23× | 1,856 B | 3,896 B | -| `TokenInitialismRatio1` | 42.68 ns | 314.91 ns | 7.38× | 280 B | 904 B | -| `TokenInitialismRatio2` | 38.45 ns | 234.78 ns | 6.11× | 272 B | 736 B | -| `TokenInitialismRatio3` | 60.71 ns | 614.33 ns | 10.12× | 392 B | 1,552 B | -| `PartialTokenInitialismRatio` | 106.53 ns | 687.16 ns | 6.45× | 568 B | 2,144 B | - -#### Cached scoring variants - -The following current-library methods have cached scorers. `Cached per call` includes creating a scorer for each operation; `reused cache` creates the scorer in benchmark setup, so its construction cost is excluded. All times are mean nanoseconds per operation. These are separate `ShortRun` measurements, so their stateless values may differ slightly from the table above. - -| Operation | Classic | Latest stateless | Cached per call | Reused cache | +| Ratio | 55.47 ± 0.54 ns | 174.65 ± 1.79 ns | 3.15× | 80 B | 320 B | +| PartialRatio | 246.00 ± 2.14 ns | 613.00 ± 8.36 ns | 2.49× | 256 B | 3368 B | +| PartialRatio (17-character pattern in 517-character text) | 1,051.00 ± 6.40 ns | 10,976.00 ± 48.70 ns | 10.44× | 1016 B | 59201 B | +| WeightedRatio | 3,125.00 ± 47.00 ns | 8,984.00 ± 25.30 ns | 2.87× | 3.59 KB | 12.47 KB | +| TokenSortRatio | 377.20 ± 1.59 ns | 1,452.70 ± 13.37 ns | 3.85× | 648 B | 2152 B | +| TokenSetRatio | 325.20 ± 3.70 ns | 2,017.90 ± 6.99 ns | 6.21× | 1048 B | 4224 B | +| PartialTokenSortRatio | 548.00 ± 3.94 ns | 1,498.70 ± 4.58 ns | 2.73× | 648 B | 2472 B | +| PartialTokenSetRatio | 832.90 ± 2.12 ns | 2,240.60 ± 15.23 ns | 2.69× | 1.8 KB | 5.58 KB | +| TokenAbbreviationRatio | 525.90 ± 16.90 ns | 1,213.70 ± 5.14 ns | 2.31× | 1.64 KB | 2.91 KB | +| PartialTokenAbbreviationRatio | 586.70 ± 4.67 ns | 1,368.00 ± 15.58 ns | 2.33× | 1.81 KB | 3.8 KB | +| TokenInitialismRatio1 | 52.89 ± 0.69 ns | 454.39 ± 5.38 ns | 8.59× | 280 B | 904 B | +| TokenInitialismRatio2 | 49.25 ± 0.12 ns | 373.43 ± 1.70 ns | 7.58× | 272 B | 736 B | +| TokenInitialismRatio3 | 86.23 ± 0.20 ns | 832.15 ± 7.13 ns | 9.65× | 392 B | 1552 B | +| PartialTokenInitialismRatio | 135.40 ± 2.10 ns | 918.80 ± 12.98 ns | 6.79× | 568 B | 2144 B | + +### Multiword PartialRatio + +Each pair consists of two independently generated strings of the same length, using an alphabet of 16 ASCII or Cyrillic characters and seed `length * 7919`. Pattern lengths exceed 64 elements, exercising multiword prefix/suffix scans and the combined mask lookup. Both libraries receive the same strings; their scores can differ because their partial-ratio algorithms differ. Times are mean microseconds per operation with 99.9% confidence intervals. Source: [PartialRatioMultiwordBenchmarks.cs](PartialRatioMultiwordBenchmarks.cs). + +| Length | Alphabet | Measured build | Classic 2.0.2 | Speedup | Allocated: measured | Allocated: Classic | +| ---: | --- | ---: | ---: | ---: | ---: | ---: | +| 65 | ASCII | 1.987 ± 0.004 μs | 25.166 ± 0.083 μs | 12.67× | 320 B | 25488 B | +| 65 | Cyrillic | 3.492 ± 0.006 μs | 25.326 ± 0.091 μs | 7.25× | 576 B | 25488 B | +| 257 | ASCII | 9.429 ± 0.082 μs | 5,422.976 ± 23.208 μs | 575.14× | 320 B | 402751 B | +| 257 | Cyrillic | 13.220 ± 0.075 μs | 5,436.591 ± 37.149 μs | 411.24× | 576 B | 402751 B | +| 1025 | ASCII | 160.978 ± 0.337 μs | 455,837.220 ± 1,739.840 μs | 2,831.67× | 320 B | 6470720 B | +| 1025 | Cyrillic | 178.948 ± 0.336 μs | 464,753.595 ± 21,788.188 μs | 2,597.14× | 576 B | 6470720 B | + +### Cached scoring variants + +`Cached per call` includes constructing a scorer for each operation. `Reused cache` creates the scorer during setup and excludes construction. All times below are mean nanoseconds per operation; stateless values come from the same measurements as the scoring table. Allocations for every method are in the generated raw reports. + +| Operation | Classic | Measured stateless | Cached per call | Reused cache | | --- | ---: | ---: | ---: | ---: | -| `Ratio` | 118.97 ns | 60.65 ns | 73.81 ns | 28.11 ns | -| `WeightedRatio` | 6,173.40 ns | 2,167.15 ns | 2,678.42 ns | 1,440.17 ns | -| `PartialTokenSetRatio` | 1,362.45 ns | 592.46 ns | 518.48 ns | 439.90 ns | -| `TokenSetRatio` | 1,143.08 ns | 337.43 ns | 271.46 ns | 216.66 ns | -| `TokenSortRatio` | 727.27 ns | 307.50 ns | 496.64 ns | 164.01 ns | - -Parallel variants are benchmarked for extraction below; these scoring benchmarks do not include a parallel scoring API. The reproduction commands generate the full BenchmarkDotNet results, including allocations for cached variants. +| Ratio | 174.65 ± 1.79 ns | 55.47 ± 0.54 ns | 88.50 ± 1.07 ns | 44.21 ± 0.27 ns | +| WeightedRatio | 8,984.00 ± 25.30 ns | 3,125.00 ± 47.00 ns | 3,350.00 ± 14.20 ns | 1,938.00 ± 15.70 ns | +| PartialTokenSetRatio | 2,240.60 ± 15.23 ns | 832.90 ± 2.12 ns | 778.20 ± 3.66 ns | 646.40 ± 4.47 ns | +| TokenSetRatio | 2,017.90 ± 6.99 ns | 325.20 ± 3.70 ns | 294.00 ± 1.49 ns | 176.30 ± 0.64 ns | +| TokenSortRatio | 1,452.70 ± 13.37 ns | 377.20 ± 1.59 ns | 550.20 ± 3.83 ns | 218.40 ± 0.55 ns | -### Extraction and distance +### Extraction -The extraction variants use the same three event records and query. The current-library cached and parallel pipelines are created during benchmark setup. `Cached` creates a scorer for each call; `reused cache` reuses a scorer from setup and excludes its construction cost. Parallel variants use at most four workers. Times are mean microseconds per operation. +Each operation compares the same query against three event records. Current-library pipelines are created in setup. `Cached` creates a scorer per extraction call; `reused cache` reuses a scorer from setup. Parallel variants use at most four workers. Times are mean microseconds per operation. This small input does not establish parallel scaling for larger collections. -| Operation | Classic | Latest | Cached | Parallel | Parallel + cached | Reused cache | Parallel + reused cache | +| Operation | Classic | Measured build | Cached | Parallel | Parallel + cached | Reused cache | Parallel + reused cache | | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | -| `ExtractOne` | 12.626 μs | 4.593 μs | 3.169 μs | 3.858 μs | 4.833 μs | 2.437 μs | 3.556 μs | -| `ExtractAll` | 12.598 μs | 4.360 μs | 3.503 μs | 4.189 μs | 4.682 μs | 2.884 μs | 3.323 μs | +| ExtractOne | 19.320 ± 0.253 μs | 5.449 ± 0.019 μs | 4.290 ± 0.015 μs | 4.441 ± 0.012 μs | 5.138 ± 0.045 μs | 3.573 ± 0.019 μs | 3.828 ± 0.012 μs | +| ExtractAll | 19.372 ± 0.176 μs | 5.633 ± 0.016 μs | 4.515 ± 0.013 μs | 4.268 ± 0.030 μs | 5.045 ± 0.050 μs | 3.655 ± 0.013 μs | 3.595 ± 0.020 μs | + +Default ExtractOne measured 3.55× faster than Classic, allocating 8.4 KB versus 27.34 KB. ExtractAll measured 3.44× faster, allocating 8.6 KB versus 27.43 KB. + +### Distance APIs + +The fixed-input static Levenshtein distance measured 126.70 ± 0.36 ns and 80 B in the current library versus 558.90 ± 3.65 ns and 320 B in Classic (4.41×). + +The large-word workload generates 20 words with seed 37 and lengths in `[3, 1024)`. Each operation computes all 400 ordered pairs. Fastenshtein and Raffinert.FuzzySharp reuse one distance instance per source word; the other implementations use static calls. Times and allocations below are for the whole batch. The `FuzzySharp` row is Classic 2.0.2; `Raffinert.FuzzySharp` is the development build. Ratio columns use `NaiveDp` as baseline. + +| Method | Mean | Error | StdDev | Ratio | Gen0 | Gen1 | Allocated | Alloc Ratio | +|--------------------- |-----------:|----------:|----------:|------:|-----------:|-----------:|------------:|------------:| +| NaiveDp | 146.787 ms | 1.2307 ms | 1.4173 ms | 1.00 | 14500.0000 | 12500.0000 | 275312720 B | 1.000 | +| FuzzySharp | 105.555 ms | 0.0896 ms | 0.1032 ms | 0.72 | - | - | 1545632 B | 0.006 | +| Fastenshtein | 97.087 ms | 0.4391 ms | 0.5056 ms | 0.66 | - | - | 33928 B | 0.000 | +| Quickenshtein | 8.226 ms | 0.0315 ms | 0.0363 ms | 0.06 | - | - | - | 0.000 | +| Raffinert.FuzzySharp | 2.399 ms | 0.0065 ms | 0.0075 ms | 0.02 | - | - | 2080 B | 0.000 | + +Additional small-word and normal-word benchmark sources cover maximum generated lengths of 64 and 128 respectively (exclusive); they are not part of these tables. Distance implementations: [FuzzySharp](https://github.com/JakeBayer/FuzzySharp), [Fastenshtein](https://github.com/DanHarltey/Fastenshtein), [Quickenshtein](https://github.com/Turnerj/Quickenshtein), and [Raffinert.FuzzySharp](https://github.com/Raffinert/FuzzySharp). + +### Scope and reports + +These are fixed-input microbenchmarks on one machine; small differences require longer runs. Partial-ratio algorithms and score rounding differ between the libraries, so this compares API workloads rather than asserting identical scores. The multiword cases compare the current library with Classic; they do not isolate the gain from the mask-lookup change alone. -Against Classic, the default latest-library methods measured **2.75×** faster for `ExtractOne` and **2.89×** for `ExtractAll` in this run. Default `ExtractOne` allocated **8.96 KB** versus **26.22 KB** for Classic; `ExtractAll` allocated **9.23 KB** versus **26.31 KB**. The reproduction command generates allocations for every variant. With only three choices, these measurements do not establish how parallel execution scales to larger collections. +### Repeatability controls -Levenshtein distance measured **122.60 ns and 80 B** in the latest library versus **367.99 ns and 320 B** in Classic, or **3.00×** faster in this case. +Ratio, Classic Ratio and Fastenshtein were measured in a separate calibration run before the full series, using the same P-core and JIT settings. The table shows calibration and full-series means with their 99.9% confidence intervals. Drift is `full-series mean / calibration mean - 1`. -Across the 17 matched latest-versus-Classic cases, the latest library had lower measured time and allocated fewer bytes. The largest measured speedup was `TokenInitialismRatio3` at 10.12×. These are specific inputs, and `ShortRun` has only three measured iterations; several confidence intervals are wide. Small differences should be rerun with a longer job before making a performance claim. +| Control | Calibration | Full series | Drift | +| --- | ---: | ---: | ---: | +| Ratio | 55.82 ± 0.75 ns | 55.47 ± 0.54 ns | -0.63% | +| RatioClassic | 174.32 ± 2.06 ns | 174.65 ± 1.79 ns | 0.19% | +| Fastenshtein | 97.150 ± 0.342 ms | 97.087 ± 0.439 ms | -0.06% | -The tables use separate runs for the basic scorer pairs, token scorers, cache variants and extraction variants. Repeated means may differ slightly between runs. +The commands below generate CSV, HTML and Markdown reports with confidence intervals in a local `BenchmarkDotNet.Artifacts` directory. Generated reports are ignored by Git; the tables above retain the measured summary. Scenarios and inputs are defined in the benchmark source files in this directory. ### Reproduce -From the repository root in PowerShell, with packages restored: +Run from the repository root in PowerShell. Clearing the optional git-baseline property selects the normal Classic comparison build. ```powershell -dotnet build FuzzySharp.Benchmarks/FuzzySharp.Benchmarks.csproj -c Release --no-restore -$env:NuGetAudit = 'false' # The online NuGet audit feed was unavailable for this run. +$env:FuzzySharpPerformanceBaseline = $null +dotnet build FuzzySharp.Benchmarks/FuzzySharp.Benchmarks.csproj -c Release -t:Rebuild -p:GeneratePackageOnBuild=false $bench = 'FuzzySharp.Benchmarks/bin/Release/net10.0/FuzzySharp.Benchmarks.dll' -dotnet $bench --filter '*RatioBenchmarks.Ratio' '*RatioBenchmarks.RatioClassic' '*PartialRatioBenchmarks.PartialRatio' '*PartialRatioBenchmarks.PartialRatioClassic' '*WeightedRatioBenchmarks.WeightedRatio' '*WeightedRatioBenchmarks.WeightedRatioClassic' --artifacts 'FuzzySharp.Benchmarks/BenchmarkDotNet.Artifacts/2026-11-24/classic-core' --join -dotnet $bench --filter '*Token*RatioBenchmarks*' '*PartialRatioLongBenchmarks*' '*ExtractOneBenchmarks.ExtractOneBy' '*ExtractOneBenchmarks.ExtractOneByClassic' '*ExtractAllBenchmarks.ExtractAllBy' '*ExtractAllBenchmarks.ExtractAllByClassic' '*LevenshteinDistanceBenchmarks.FuzzySharpDistance' '*LevenshteinDistanceBenchmarks.FuzzySharpClassicDistance' --artifacts 'FuzzySharp.Benchmarks/BenchmarkDotNet.Artifacts/2026-11-24/classic-comparison' --join -dotnet $bench --filter '*.RatioBenchmarks.*' '*.WeightedRatioBenchmarks.*' --artifacts 'FuzzySharp.Benchmarks/BenchmarkDotNet.Artifacts/2026-11-24/scoring-cache-variants' --join -dotnet $bench --filter '*ExtractOneBenchmarks*' '*ExtractAllBenchmarks*' --artifacts 'FuzzySharp.Benchmarks/BenchmarkDotNet.Artifacts/2026-11-24/extraction-variants' --join +$output = 'FuzzySharp.Benchmarks/BenchmarkDotNet.Artifacts/2026-11-28-pcore' + +dotnet $bench --filter '*.RatioBenchmarks.Ratio' '*.RatioBenchmarks.RatioClassic' '*.LevenshteinDistance.LevenshteinLarge.Fastenshtein' --affinity 1024 --envVars DOTNET_TieredCompilation:0 --iterationCount 10 --iterationTime 300 --warmupCount 6 --launchCount 2 --outliers DontRemove --artifacts "$output/pilot" + +$sequential = @( + '*.RatioBenchmarks.*', '*.PartialRatioBenchmarks.*', '*.PartialRatioLongBenchmarks.*', + '*.PartialRatioMultiwordBenchmarks.*', '*.WeightedRatioBenchmarks.*', '*Token*RatioBenchmarks*', + '*.ExtractOneBenchmarks.ExtractOneBy', '*.ExtractOneBenchmarks.ExtractOneByClassic', + '*.ExtractOneBenchmarks.ExtractOneByCached', '*.ExtractOneBenchmarks.ExtractOneByAcrossRunsCached', + '*.ExtractAllBenchmarks.ExtractAllBy', '*.ExtractAllBenchmarks.ExtractAllByClassic', + '*.ExtractAllBenchmarks.ExtractAllByCached', '*.ExtractAllBenchmarks.ExtractAllByAcrossRunsCached', + '*.LevenshteinDistanceBenchmarks.FuzzySharpDistance', + '*.LevenshteinDistanceBenchmarks.FuzzySharpClassicDistance', + '*.LevenshteinDistance.LevenshteinLarge.*' +) +dotnet $bench --filter $sequential --affinity 1024 --envVars DOTNET_TieredCompilation:0 --iterationCount 10 --iterationTime 300 --warmupCount 6 --launchCount 2 --outliers DontRemove --artifacts "$output/sequential" + +dotnet $bench --filter '*.ExtractOneBenchmarks.*Parallel*' '*.ExtractAllBenchmarks.*Parallel*' --affinity 15360 --envVars DOTNET_TieredCompilation:0 --iterationCount 10 --iterationTime 300 --warmupCount 6 --launchCount 2 --outliers DontRemove --artifacts "$output/parallel" ``` -For a stable comparison, run on an otherwise idle machine. BenchmarkDotNet records the environment and the full measurement distribution in its generated reports. +Use a new output directory for later runs to keep reports separate. Verify core topology and choose suitable affinity masks for your machine; these masks refer to this host only. BenchmarkDotNet records the environment and measurement distribution in every report. diff --git a/FuzzySharp.Test/FuzzyTests/LcsOptimizationTests.cs b/FuzzySharp.Test/FuzzyTests/LcsOptimizationTests.cs new file mode 100644 index 0000000..faf650b --- /dev/null +++ b/FuzzySharp.Test/FuzzyTests/LcsOptimizationTests.cs @@ -0,0 +1,477 @@ +using System; +using System.Linq; +using Raffinert.FuzzySharp.SimilarityRatio.Scorer.StrategySensitive; +using Raffinert.FuzzySharp.SimilarityRatio.Strategy.Generic; +using Raffinert.FuzzySharp.Utils; +using Xunit; + +namespace Raffinert.FuzzySharp.Test.FuzzyTests; + +public class LcsOptimizationTests +{ + [Theory] + [InlineData(63)] + [InlineData(64)] + [InlineData(65)] + [InlineData(127)] + [InlineData(128)] + [InlineData(129)] + [InlineData(257)] + [InlineData(1023)] + [InlineData(1024)] + [InlineData(1025)] + [InlineData(2049)] + public void LcsAndMatrixMatchDynamicProgramming(int length) + { + var random = new Random(length); + for (int sample = 0; sample < 8; sample++) + { + var a = RandomSequence(random, length); + var b = RandomSequence(random, length + 17); + int expected = ReferenceLcs(a, b); + + Assert.Equal(expected, LongestCommonSubsequence.Similarity(a, b)); + Assert.Equal(expected, LongestCommonSubsequence.Matrix(a, b).Sim); + Assert.Equal(a.Length + b.Length - 2 * expected, Indel.Distance(a, b)); + } + + // Exercise carries across a full machine word with dense masks. + var repeated = new int[length]; + var shifted = new int[length + 1]; + shifted[0] = 1; + Assert.Equal(length, LongestCommonSubsequence.Similarity(repeated, shifted)); + Assert.Equal(length, LongestCommonSubsequence.Matrix(repeated, shifted).Sim); + } + + [Theory] + [InlineData(1)] + [InlineData(7)] + [InlineData(8)] + [InlineData(9)] + [InlineData(16)] + [InlineData(43)] + [InlineData(64)] + [InlineData(65)] + [InlineData(129)] + [InlineData(257)] + [InlineData(1023)] + [InlineData(1024)] + [InlineData(1025)] + [InlineData(2049)] + public void PartialRatioEdgesMatchReferenceAndPreserveAlignment(int length) + { + var random = new Random(7919 + length); + for (int sample = 0; sample < 5; sample++) + { + int[] a = RandomSequence(random, length); + int[] b = RandomSequence(random, length); + var forward = ReferenceEdgeAlignment(a, b); + var backward = ReferenceEdgeAlignment(b, a); + var actual = PartialRatioStrategy.PartialRatioAlignment(a, b); + + if (backward.Score > forward.Score) + { + Assert.Equal(backward.Score, actual.Score, 12); + Assert.Equal(backward.Start, actual.SrcStart); + Assert.Equal(backward.End, actual.SrcEnd); + Assert.Equal(0, actual.DestStart); + Assert.Equal(length, actual.DestEnd); + } + else + { + Assert.Equal(forward.Score, actual.Score, 12); + Assert.Equal(0, actual.SrcStart); + Assert.Equal(length, actual.SrcEnd); + Assert.Equal(forward.Start, actual.DestStart); + Assert.Equal(forward.End, actual.DestEnd); + } + } + } + + [Theory] + [InlineData("abc", "bcd")] + [InlineData("abc", "xab")] + [InlineData("abc", "xyz")] + [InlineData("apple", "pineapple")] + [InlineData("абвг", "гдеабв")] + [InlineData("the quick brown fox jumps over the lazy dog", "the lazy dog jumps over the quick brown fox")] + [InlineData("abcdefgh", "zzcdefgh")] + [InlineData("abcdefghi", "zzcdefghi")] + [InlineData("abcdefghi", "xxxxxxxxa")] + [InlineData("abcdefghi", "zzzzzzzzzzzz")] + [InlineData("абвгґдеєж", "жєедґгвба")] + public void PartialRatioMatchesExhaustiveWindowSearch(string a, string b) + { + var first = Array.ConvertAll(a.ToCharArray(), c => (int)c); + var second = Array.ConvertAll(b.ToCharArray(), c => (int)c); + double expected = ReferencePartialRatio(first, second); + Assert.Equal(expected, Fuzz.PartialRatio(a, b), 12); + Assert.Equal(expected, PartialRatioStrategy.Calculate(first, second), 12); + Assert.Equal(expected, Fuzz.PartialRatio(b, a), 12); + } + + [Theory] + [InlineData("", "")] + [InlineData(" ", "a")] + [InlineData("apple", "banana")] + [InlineData("apple banana", "apple banana orange")] + [InlineData("apple apple banana", "banana apple")] + [InlineData("apple banana orange", "apple banana lemon")] + [InlineData("яблуко груша", "яблуко слива")] + [InlineData("a b c", "d e f")] + [InlineData("banana apple", "banana banana apple orange")] + [InlineData("яблуко груша", "слива груша яблуко")] + public void TokenSetPrefixFormulaMatchesUnoptimizedScorer(string a, string b) + { + double expected = new ReferenceTokenSetScorer().Score(a, b); + using var cached = new CachedTokenSetScorer(a); + Assert.Equal(expected, Fuzz.TokenSetRatio(a, b)); + Assert.Equal(expected, cached.Score(b)); + Assert.Equal(expected, Fuzz.TokenSetRatio(b, a)); + } + + // The public extension point still evaluates all three comparisons. + [Theory] + [InlineData("apple banana", "apple orange")] + [InlineData("apple", "apple orange")] + [InlineData("apple orange", "apple")] + [InlineData("apple", "apple")] + public void CustomTokenSetScorerStillInvokesItsOwnStrategy(string a, string b) + { + var scorer = new CountingTokenSetScorer(); + Assert.Equal(42, scorer.Score(a, b)); + Assert.Equal(3, scorer.Calls); + } + + [Theory] + [InlineData("apple banana", "apple orange")] + [InlineData("apple", "apple orange")] + [InlineData("apple orange", "apple")] + [InlineData("apple", "apple")] + public void CustomCachedTokenSetScorerStillInvokesItsOwnStrategy(string a, string b) + { + using var scorer = new CountingCachedTokenSetScorer(a); + Assert.Equal(142, scorer.Score(b)); + Assert.Equal(3, scorer.Calls); + Assert.Equal(142, scorer.Score(b)); + Assert.Equal(6, scorer.Calls); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(8)] + [InlineData(9)] + [InlineData(63)] + [InlineData(64)] + [InlineData(65)] + [InlineData(1023)] + [InlineData(1024)] + [InlineData(1025)] + [InlineData(2049)] + public void ReversedPatternVectorsMatchExplicitReversal(int length) + { + const string alphabet = "abяєґ"; + var chars = Enumerable.Range(0, length).Select(i => alphabet[i % alphabet.Length]).ToArray(); + var reversed = chars.Reverse().ToArray(); + using var actual = PatternMatchVector.CreateReversed(chars); + using var expected = PatternMatchVector.Create(reversed); + var ints = Array.ConvertAll(chars, c => (int)c); + using var generic = PatternMatchVector.CreateReversed(ints); + if (length > 0 && length <= 64) + { + using var inPlace = PatternMatchVector.Create(chars); + using var genericInPlace = PatternMatchVector.Create(ints); + PatternMatchVector.ReverseSingleWord(inPlace); + PatternMatchVector.ReverseSingleWord(genericInPlace); + foreach (var symbol in alphabet + "z") + { + Assert.Equal(expected.GetOrZero(symbol).ToArray(), inPlace.GetOrZero(symbol).ToArray()); + Assert.Equal(expected.GetOrZero(symbol).ToArray(), genericInPlace.GetOrZero(symbol)[..1].ToArray()); + } + } + foreach (var symbol in alphabet + "z") + { + Assert.Equal(expected.ContainsKey(symbol), actual.ContainsKey(symbol)); + Assert.Equal(expected.ContainsKey(symbol), generic.ContainsKey(symbol)); + Assert.Equal(expected.GetOrZero(symbol).ToArray(), actual.GetOrZero(symbol).ToArray()); + // Generic missing-key masks can expose the pool's rounded-up rental. + Assert.Equal(expected.GetOrZero(symbol).ToArray(), generic.GetOrZero(symbol)[..generic.Blocks].ToArray()); + } + } + + [Theory] + [InlineData(63, 1)] + [InlineData(64, 2)] + [InlineData(65, 17)] + [InlineData(65, 131)] + [InlineData(127, 64)] + [InlineData(128, 129)] + [InlineData(129, 257)] + [InlineData(257, 33)] + [InlineData(1023, 1)] + [InlineData(1024, 2)] + [InlineData(1025, 17)] + [InlineData(2049, 3)] + public void PartialRatioLongWindowsMatchExhaustiveDynamicProgramming(int length, int extraLength) + { + var random = new Random(length * 7919 + extraLength); + var pattern = RandomSequence(random, length); + var text = RandomSequence(random, length + extraLength); + double expected = ReferencePartialRatio(pattern, text); + + AssertWindowAlignment(pattern, text, expected); + } + + [Theory] + [InlineData(63, 0, 17)] + [InlineData(64, 1, 17)] + [InlineData(65, 17, 0)] + [InlineData(65, 64, 65)] + [InlineData(129, 65, 33)] + [InlineData(1025, 17, 33)] + public void PartialRatioLongWindowsFindExactInteriorAndLastWindows(int length, int before, int after) + { + var pattern = Enumerable.Range(0, length).ToArray(); + var text = Enumerable.Repeat(-1, before).Concat(pattern).Concat(Enumerable.Repeat(-1, after)).ToArray(); + var alignment = AssertWindowAlignment(pattern, text, 100); + Assert.Equal(before, alignment.DestStart); + Assert.Equal(before + length, alignment.DestEnd); + } + + [Theory] + [InlineData(63)] + [InlineData(64)] + [InlineData(65)] + [InlineData(129)] + [InlineData(1025)] + public void PartialRatioLongWindowsFindNearExactInteriorWithoutRoundingToPerfect(int length) + { + var pattern = Enumerable.Range(0, length).ToArray(); + var candidate = (int[])pattern.Clone(); + candidate[length / 2] = -2; + var text = Enumerable.Repeat(-1, 33).Concat(candidate).Concat(Enumerable.Repeat(-1, 35)).ToArray(); + double expected = ReferenceRatio(pattern, candidate); + + var alignment = AssertWindowAlignment(pattern, text, expected); + Assert.True(alignment.Score < 100); + Assert.Equal(33, alignment.DestStart); + Assert.Equal(33 + length, alignment.DestEnd); + } + + [Theory] + [InlineData(63, false)] + [InlineData(65, false)] + [InlineData(1025, false)] + [InlineData(65, true)] + [InlineData(2049, true)] + public void PartialRatioLongEdgesCanBeatInteriorWindows(int length, bool suffix) + { + var pattern = Enumerable.Range(0, length).ToArray(); + var text = suffix + ? Enumerable.Repeat(-1, 70).Concat(pattern.Skip(1)).ToArray() + : pattern.Take(length - 1).Concat(Enumerable.Repeat(-1, 70)).ToArray(); + double expected = 100 * (1.0 - 1.0 / (2 * length - 1)); + var alignment = AssertWindowAlignment(pattern, text, expected); + Assert.Equal(suffix ? 70 : 0, alignment.DestStart); + Assert.Equal(suffix ? text.Length : length - 1, alignment.DestEnd); + } + + [Theory] + [InlineData(65)] + [InlineData(1025)] + public void PartialRatioLongWindowsKeepFirstExactMatchOnTies(int length) + { + var pattern = Enumerable.Range(0, length).ToArray(); + var text = pattern.Concat(Enumerable.Repeat(-1, 37)).Concat(pattern).ToArray(); + var alignment = AssertWindowAlignment(pattern, text, 100); + Assert.Equal(0, alignment.DestStart); + Assert.Equal(length, alignment.DestEnd); + } + +#if NET8_0_OR_GREATER + [Theory] + [InlineData(9, false)] + [InlineData(63, false)] + [InlineData(64, false)] + [InlineData(9, true)] + [InlineData(64, true)] + public void PartialRatioSingleWordEdgesDoNotAllocateAnotherPatternVector(int length, bool unicode) + { + string alphabet = unicode ? "абвгґдеє" : "abcdefgh"; + string query = new string(Enumerable.Range(0, length).Select(i => alphabet[i % alphabet.Length]).ToArray()); + string candidate = query.Substring(0, length - 1) + "!"; + for (int i = 0; i < 256; i++) + Fuzz.PartialRatio(query, candidate); + + const int repetitions = 128; + long vectorBudget = long.MaxValue; + long allocated = long.MaxValue; + for (int sample = 0; sample < 8; sample++) + { + long start = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < repetitions; i++) + { + using (PatternMatchVector.Create(query)) { } + using (PatternMatchVector.Create(candidate)) { } + } + vectorBudget = Math.Min(vectorBudget, GC.GetAllocatedBytesForCurrentThread() - start); + + start = GC.GetAllocatedBytesForCurrentThread(); + for (int i = 0; i < repetitions; i++) + Fuzz.PartialRatio(query, candidate); + allocated = Math.Min(allocated, GC.GetAllocatedBytesForCurrentThread() - start); + } + + // Equal non-exact inputs require two directions, each with its own + // query vector. Neither suffix scan should allocate a second vector. + // Use the minimum of several batches so a transient pool refill after + // a Gen2 trim does not determine the result. Lower allocations are OK. + Assert.InRange(allocated, 0, vectorBudget); + } +#endif + + private static PartialRatioStrategy.ScoreAlignment AssertWindowAlignment(int[] pattern, int[] text, double expected) + { + var actual = PartialRatioStrategy.PartialRatioAlignment(pattern, text); + Assert.Equal(expected, actual.Score, 12); + Assert.Equal(0, actual.SrcStart); + Assert.Equal(pattern.Length, actual.SrcEnd); + Assert.InRange(actual.DestStart, 0, text.Length - 1); + Assert.InRange(actual.DestEnd, actual.DestStart + 1, text.Length); + Assert.Equal(actual.Score, ReferenceRatio(pattern, text.AsSpan(actual.DestStart, actual.DestEnd - actual.DestStart)), 12); + + var swapped = PartialRatioStrategy.PartialRatioAlignment(text, pattern); + Assert.Equal(actual.Score, swapped.Score); + Assert.Equal(actual.DestStart, swapped.SrcStart); + Assert.Equal(actual.DestEnd, swapped.SrcEnd); + Assert.Equal(actual.SrcStart, swapped.DestStart); + Assert.Equal(actual.SrcEnd, swapped.DestEnd); + + var first = new string(Array.ConvertAll(pattern, value => (char)(0x1000 + value))); + var second = new string(Array.ConvertAll(text, value => (char)(0x1000 + value))); + var characters = PartialRatioStrategy.PartialRatioAlignment(first.AsSpan(), second.AsSpan()); + Assert.Equal(actual.Score, characters.Score, 12); + Assert.Equal(actual.DestStart, characters.DestStart); + Assert.Equal(actual.DestEnd, characters.DestEnd); + Assert.Equal(expected, Fuzz.PartialRatio(first, second), 12); + Assert.Equal(expected, Fuzz.PartialRatio(second, first), 12); + return actual; + } + + private sealed class ReferenceTokenSetScorer : TokenSetScorerBase + { + protected override global::Raffinert.FuzzySharp.Scorer Scorer => Fuzz.Ratio; + } + + private sealed class CountingTokenSetScorer : TokenSetScorerBase + { + public int Calls { get; private set; } + protected override global::Raffinert.FuzzySharp.Scorer Scorer => (_, _) => + { + Calls++; + return 42; + }; + } + + private sealed class CountingCachedTokenSetScorer(string query) : CachedTokenSetScorerBase(query) + { + public int Calls { get; private set; } + protected override global::Raffinert.FuzzySharp.Scorer Scorer => (_, _) => + { + Calls++; + return 142; + }; + } + + private static int[] RandomSequence(Random random, int length) + { + var result = new int[length]; + for (int i = 0; i < result.Length; i++) + result[i] = random.Next(8); + return result; + } + + private static int ReferenceLcs(ReadOnlySpan a, ReadOnlySpan b) + { + var row = new int[b.Length + 1]; + foreach (int x in a) + { + int diagonal = 0; + for (int j = 0; j < b.Length; j++) + { + int above = row[j + 1]; + row[j + 1] = x == b[j] + ? diagonal + 1 + : Math.Max(above, row[j]); + diagonal = above; + } + } + return row[b.Length]; + } + + private static double ReferenceRatio(ReadOnlySpan a, ReadOnlySpan b) + { + int total = a.Length + b.Length; + return 100 * (1.0 - (total - 2 * ReferenceLcs(a, b)) / (double)total); + } + + private static (double Score, int Start, int End) ReferenceEdgeAlignment( + ReadOnlySpan a, ReadOnlySpan b) + { + double best = 0; + int start = 0, end = a.Length; + var prefixes = ReferencePrefixRatios(a, b[..(a.Length - 1)], reverse: false); + var suffixes = ReferencePrefixRatios(a, b[(b.Length - a.Length)..], reverse: true); + for (int i = 1; i < a.Length; i++) + { + double score = prefixes[i - 1]; + if (score > best) + (best, start, end) = (score, 0, i); + } + for (int i = b.Length - a.Length; i < b.Length; i++) + { + double score = suffixes[b.Length - i - 1]; + if (score > best) + (best, start, end) = (score, i, b.Length); + } + return (best, start, end); + } + + // Independent quadratic DP reference, keeping scores for every prefix. + // This also makes the 1024/1025 pooled-row boundary practical to test. + private static double[] ReferencePrefixRatios(ReadOnlySpan pattern, ReadOnlySpan text, bool reverse) + { + var row = new int[pattern.Length + 1]; + var scores = new double[text.Length]; + for (int i = 0; i < text.Length; i++) + { + int symbol = text[reverse ? text.Length - i - 1 : i]; + int diagonal = 0; + for (int j = 0; j < pattern.Length; j++) + { + int above = row[j + 1]; + int item = pattern[reverse ? pattern.Length - j - 1 : j]; + row[j + 1] = item == symbol ? diagonal + 1 : Math.Max(above, row[j]); + diagonal = above; + } + int total = pattern.Length + i + 1; + scores[i] = 100 * (1.0 - (total - 2 * row[pattern.Length]) / (double)total); + } + return scores; + } + + private static double ReferencePartialRatio(ReadOnlySpan a, ReadOnlySpan b) + { + if (a.Length > b.Length) + return ReferencePartialRatio(b, a); + + double best = ReferenceEdgeAlignment(a, b).Score; + for (int i = 0; i <= b.Length - a.Length; i++) + best = Math.Max(best, ReferenceRatio(a, b.Slice(i, a.Length))); + + if (a.Length == b.Length) + best = Math.Max(best, ReferenceEdgeAlignment(b, a).Score); + return best; + } +} diff --git a/FuzzySharp.Test/FuzzyTests/MultiwordRowTests.cs b/FuzzySharp.Test/FuzzyTests/MultiwordRowTests.cs new file mode 100644 index 0000000..8b8c89b --- /dev/null +++ b/FuzzySharp.Test/FuzzyTests/MultiwordRowTests.cs @@ -0,0 +1,110 @@ +using System; +using System.Linq; +using Raffinert.FuzzySharp.Utils; +using Xunit; + +namespace Raffinert.FuzzySharp.Test.FuzzyTests; + +public class MultiwordRowTests +{ + [Fact] + public void RowUpdatePropagatesEveryByteCarryCombination() + { + var state = new ulong[3]; + var matches = new ulong[3]; + const ulong low = (1UL << 56) - 1; + for (int incoming = 0; incoming <= 1; incoming++) + for (int value = 0; value < 256; value++) + for (int mask = 0; mask < 256; mask++) + { + // The first word produces the incoming carry. Ones in the low + // 56 bits propagate it into the byte under test. The final word + // exposes the outgoing carry instead of discarding it. + state[0] = incoming == 0 ? 0 : ulong.MaxValue; + state[1] = ((ulong)value << 56) | low; + state[2] = 0; + matches[0] = (ulong)incoming; + matches[1] = (ulong)mask << 56; + int u = value & mask; + int sum = value + u + incoming; + ulong expected = ((ulong)((sum & 255) | (value - u)) << 56) | low; + + LongestCommonSubsequence.AdvanceMultiWordRow(state, matches); + + Assert.Equal(expected, state[1]); + Assert.Equal((ulong)(sum >> 8), state[2]); + } + } + + [Theory] + [InlineData(1)] + [InlineData(2)] + [InlineData(8)] + [InlineData(32)] + public void RowUpdateMatchesIndependentBitwiseFullAdder(int words) + { + var random = new Random(390004 + words); + var bytes = new byte[8]; + for (int sample = 0; sample < 1000; sample++) + { + var state = new ulong[words]; + var matches = new ulong[words]; + for (int i = 0; i < words; i++) + { + random.NextBytes(bytes); + state[i] = BitConverter.ToUInt64(bytes, 0); + random.NextBytes(bytes); + matches[i] = BitConverter.ToUInt64(bytes, 0); + } + var expected = new ulong[words]; + ulong carry = 0; + for (int word = 0; word < words; word++) + { + ulong s = state[word], u = s & matches[word], sum = 0; + for (int bit = 0; bit < 64; bit++) + { + ulong total = ((s >> bit) & 1) + ((u >> bit) & 1) + carry; + sum |= (total & 1) << bit; + carry = total >> 1; + } + expected[word] = sum | (s - u); + } + + LongestCommonSubsequence.AdvanceMultiWordRow(state, matches); + + Assert.Equal(expected, state); + } + } + + [Theory] + [InlineData(1)] + [InlineData(65)] + [InlineData(257)] + [InlineData(1025)] + public void InternalMaskLookupReturnsPresenceAndTheOriginalMask(int length) + { + const string alphabet = "abяєґ"; + var pattern = Enumerable.Range(0, length).Select(i => alphabet[i % alphabet.Length]).ToArray(); + pattern[length - 1] = 'Z'; // Present only in the final word for long patterns. + using var characters = PatternMatchVector.Create(pattern); + using var generic = PatternMatchVector.Create(Array.ConvertAll(pattern, c => (int)c)); + var characterLookup = (IPatternMatchVectorImpl)characters; + var genericLookup = (IPatternMatchVectorImpl)generic; + foreach (char symbol in alphabet + "Zz") + { + bool expected = Array.IndexOf(pattern, symbol) >= 0; + Assert.Equal(expected, characterLookup.TryGetMask(symbol, out var characterMask)); + Assert.Equal(expected, genericLookup.TryGetMask(symbol, out var genericMask)); + if (expected) + { + Assert.Equal(characters.GetOrZero(symbol).ToArray(), characterMask.ToArray()); + Assert.Equal(characterMask.ToArray(), genericMask.ToArray()); + } + else + { + Assert.True(characterMask.IsEmpty); + Assert.True(genericMask.IsEmpty); + } + } + } +} diff --git a/FuzzySharp/FuzzySharp.csproj b/FuzzySharp/FuzzySharp.csproj index d06d0a0..b10d1fb 100644 --- a/FuzzySharp/FuzzySharp.csproj +++ b/FuzzySharp/FuzzySharp.csproj @@ -1,10 +1,10 @@  - 6.0.2.0 - 6.0.2 - 6.0.2 - 6.0.2.0 + 6.0.3.0 + 6.0.3 + 6.0.3 + 6.0.3.0 Yevhen Cherkes;Jacob Bayer diff --git a/FuzzySharp/LongestCommonSubsequence.Static.cs b/FuzzySharp/LongestCommonSubsequence.Static.cs index 989d22d..8642c79 100644 --- a/FuzzySharp/LongestCommonSubsequence.Static.cs +++ b/FuzzySharp/LongestCommonSubsequence.Static.cs @@ -379,30 +379,7 @@ internal static int BlockSimilarityMultipleULongs(IPatternMatchVector s1Ve { var U = s1Vector.GetOrZero(s2[chIdx]); - // big-integer add/subtract using u = S & U - ulong carry = 0; - ulong borrow = 0; - for (int b = 0; b < blockCount; b++) - { - ulong s = S[b]; - ulong u = s & U[b]; - - // Sum = S + u - ulong t = unchecked(s + u); - ulong c1 = t < s ? 1UL : 0UL; - ulong sum = unchecked(t + carry); - ulong c2 = sum < t ? 1UL : 0UL; - carry = c1 | c2; - - // Diff = S - u - ulong t1 = unchecked(s - u); - ulong b1 = s < u ? 1UL : 0UL; - ulong diff = unchecked(t1 - borrow); - ulong b2 = t1 < borrow ? 1UL : 0UL; - borrow = b1 | b2; - // update S = Sum | Diff - S[b] = sum | diff; - } + AdvanceMultiWordRow(S, U); } // --- 4) count zero bits in the lower len1 positions of S --- @@ -414,14 +391,31 @@ internal static int BlockSimilarityMultipleULongs(IPatternMatchVector s1Ve } } - private static int CountZeroBits(ulong x, int length) + // u is a bit subset of s: s - u is s & ~u and can never borrow. + // Only the addition needs carry propagation between words. + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static void AdvanceMultiWordRow(Span state, ReadOnlySpan matches) + { + ulong carry = 0; + for (int b = 0; b < state.Length; b++) + { + ulong s = state[b]; + ulong u = s & matches[b]; + ulong t = unchecked(s + u); + ulong sum = unchecked(t + carry); + carry = (t < s || sum < t) ? 1UL : 0UL; + state[b] = sum | (s & ~u); + } + } + + internal static int CountZeroBits(ulong x, int length) { // invert and mask ulong inv = ~x & (length == 64 ? ulong.MaxValue : (1UL << length) - 1UL); return Polyfill.PopCount(inv); } - private static int CountZeroBits(ReadOnlySpan S, int length) + internal static int CountZeroBits(ReadOnlySpan S, int length) { int fullBlocks = length / 64; int remBits = length % 64; @@ -470,31 +464,7 @@ private static (int Sim, List Matrix) MatrixMultipleULongs( // load mask for y var U = s1Vector.GetOrZero(y); - // big-integer add/subtract using u = S & U - ulong carry = 0; - ulong borrow = 0; - for (int b = 0; b < blocks; b++) - { - // u = S & U - ulong s = S[b]; - ulong u = s & U[b]; - - // Sum = S + u - ulong t = unchecked(s + u); - ulong c1 = t < s ? 1UL : 0UL; - ulong sum = unchecked(t + carry); - ulong c2 = sum < t ? 1UL : 0UL; - carry = c1 | c2; - - // Diff = S - u - ulong t1 = unchecked(s - u); - ulong b1 = s < u ? 1UL : 0UL; - ulong diff = unchecked(t1 - borrow); - ulong b2 = t1 < borrow ? 1UL : 0UL; - borrow = b1 | b2; - // update S = Sum | Diff - S[b] = sum | diff; - } + AdvanceMultiWordRow(S, U); // snapshot row matrix.Add((ulong[])S.Clone()); diff --git a/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/CachedTokenSetScorer.cs b/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/CachedTokenSetScorer.cs index 712cd5e..1479e82 100644 --- a/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/CachedTokenSetScorer.cs +++ b/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/CachedTokenSetScorer.cs @@ -5,4 +5,6 @@ namespace Raffinert.FuzzySharp.SimilarityRatio.Scorer.StrategySensitive; public sealed class CachedTokenSetScorer(string input1) : CachedTokenSetScorerBase(input1) { protected override FuzzySharp.Scorer Scorer => DefaultRatioStrategy.Calculate; -} \ No newline at end of file + + internal override bool UsesBuiltInIndelRatio => true; +} diff --git a/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/CachedTokenSetScorerBase.cs b/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/CachedTokenSetScorerBase.cs index 39827aa..5e65e7f 100644 --- a/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/CachedTokenSetScorerBase.cs +++ b/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/CachedTokenSetScorerBase.cs @@ -28,19 +28,16 @@ public double Score(string input2) difference1.Add(token); } - intersection.Sort(); - - var sortedIntersection = string.Join(" ", intersection); - var sortedDiff1To2 = TokenSetScorerHelpers.JoinIntersectionAndDifference(sortedIntersection, difference1); - var sortedDiff2To1 = TokenSetScorerHelpers.JoinIntersectionAndDifference(sortedIntersection, tokens2); - - var score1 = Scorer(sortedIntersection, sortedDiff1To2); - var score2 = Scorer(sortedIntersection, sortedDiff2To1); - var score3 = Scorer(sortedDiff1To2, sortedDiff2To1); - - return Math.Max(score1, Math.Max(score2, score3)); + return TokenSetScorerHelpers.Score(Scorer, UsesBuiltInIndelRatio, intersection, difference1, tokens2); } + /// + /// True only when the scorer strategy is the built-in Indel ratio, + /// which lets token-set scoring use exact length-based shortcuts. + /// Custom and partial scorers keep calling their own strategy. + /// + internal virtual bool UsesBuiltInIndelRatio => false; + public void Dispose() { } diff --git a/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/TokenSetScorer.cs b/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/TokenSetScorer.cs index 8203af8..15d2545 100644 --- a/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/TokenSetScorer.cs +++ b/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/TokenSetScorer.cs @@ -5,4 +5,6 @@ namespace Raffinert.FuzzySharp.SimilarityRatio.Scorer.StrategySensitive; public sealed class TokenSetScorer : TokenSetScorerBase { protected override FuzzySharp.Scorer Scorer => DefaultRatioStrategy.Calculate; -} \ No newline at end of file + + internal override bool UsesBuiltInIndelRatio => true; +} diff --git a/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/TokenSetScorerBase.cs b/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/TokenSetScorerBase.cs index 18cc872..c4fccd9 100644 --- a/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/TokenSetScorerBase.cs +++ b/FuzzySharp/SimilarityRatio/Scorer/StrategySensitive/TokenSet/TokenSetScorerBase.cs @@ -18,24 +18,68 @@ public override double Score(string input1, string input2) var intersection = GetIntersectionAndExcept(tokens1, tokens2); - intersection.Sort(); - var sortedIntersection = string.Join(" ", intersection); - var sortedDiff1To2 = TokenSetScorerHelpers.JoinIntersectionAndDifference(sortedIntersection, tokens1); - var sortedDiff2To1 = TokenSetScorerHelpers.JoinIntersectionAndDifference(sortedIntersection, tokens2); - - var score1 = Scorer(sortedIntersection, sortedDiff1To2); - var score2 = Scorer(sortedIntersection, sortedDiff2To1); - var score3 = Scorer(sortedDiff1To2, sortedDiff2To1); - - return Math.Max(score1, Math.Max(score2, score3)); + return TokenSetScorerHelpers.Score(Scorer, UsesBuiltInIndelRatio, intersection, tokens1, tokens2); } + /// + /// True only when the scorer strategy is the built-in Indel ratio, + /// which lets token-set scoring use exact length-based shortcuts. + /// Custom and partial scorers keep calling their own strategy. + /// + internal virtual bool UsesBuiltInIndelRatio => false; + private static List GetIntersectionAndExcept(HashSet first, HashSet second) => TokenSetScorerHelpers.GetIntersectionAndExcept(first, second); } internal static class TokenSetScorerHelpers { + /// + /// Shared token-set scoring after the intersection and both differences are known. + /// The collections are consumed: and list differences are sorted in place. + /// + internal static double Score(FuzzySharp.Scorer scorer, bool usesBuiltInIndelRatio, + List intersection, ICollection difference1, ICollection difference2) + { + // With the Indel ratio, a nonempty intersection compared with itself scores 100. + if (usesBuiltInIndelRatio && intersection.Count != 0 && (difference1.Count == 0 || difference2.Count == 0)) + return 100; + + intersection.Sort(); + var sortedIntersection = string.Join(" ", intersection); + var sortedDiff1To2 = JoinIntersectionAndDifference(sortedIntersection, difference1); + var sortedDiff2To1 = JoinIntersectionAndDifference(sortedIntersection, difference2); + + double score1, score2; + if (usesBuiltInIndelRatio) + { + score1 = PrefixRatio(sortedIntersection.Length, sortedDiff1To2.Length); + score2 = PrefixRatio(sortedIntersection.Length, sortedDiff2To1.Length); + } + else + { + score1 = scorer(sortedIntersection, sortedDiff1To2); + score2 = scorer(sortedIntersection, sortedDiff2To1); + } + + var score3 = scorer(sortedDiff1To2, sortedDiff2To1); + + return Math.Max(score1, Math.Max(score2, score3)); + } + + internal static double PrefixRatio(int prefixLength, int combinedLength) + { + // DefaultRatioStrategy returns zero when either input is empty. + if (prefixLength == 0 || combinedLength == 0) + return 0; + + // The intersection is a prefix of each combined string, so the + // Indel distance is exactly the difference in their lengths. + // Keep the same arithmetic order as the normal Indel ratio. + return 100 * (1.0 - (combinedLength - prefixLength) / + (double)(combinedLength + prefixLength)); + } + internal static List GetIntersectionAndExcept(HashSet first, HashSet second) { var intersection = new List(Math.Min(first.Count, second.Count)); @@ -55,33 +99,17 @@ internal static List GetIntersectionAndExcept(HashSet first, Has return intersection; } - internal static string JoinIntersectionAndDifference(string sortedIntersection, HashSet difference) + internal static string JoinIntersectionAndDifference(string sortedIntersection, ICollection difference) { if (difference.Count == 0) return sortedIntersection; - var sortedDifference = JoinSorted(difference); - return sortedIntersection.Length == 0 - ? sortedDifference - : string.Concat(sortedIntersection, " ", sortedDifference); - } - - internal static string JoinIntersectionAndDifference(string sortedIntersection, List difference) - { - if (difference.Count == 0) - return sortedIntersection; - - difference.Sort(); - var sortedDifference = string.Join(" ", difference); + // A list difference is owned by the caller's scoring pass and can be sorted in place. + var sortedTokens = difference as List ?? new List(difference); + sortedTokens.Sort(); + var sortedDifference = string.Join(" ", sortedTokens); return sortedIntersection.Length == 0 ? sortedDifference : string.Concat(sortedIntersection, " ", sortedDifference); } - - private static string JoinSorted(IEnumerable tokens) - { - var sortedTokens = new List(tokens); - sortedTokens.Sort(); - return string.Join(" ", sortedTokens); - } } diff --git a/FuzzySharp/SimilarityRatio/Strategy/Generic/PartialRatioStrategyT.cs b/FuzzySharp/SimilarityRatio/Strategy/Generic/PartialRatioStrategyT.cs index 8fb53f3..a4eec92 100644 --- a/FuzzySharp/SimilarityRatio/Strategy/Generic/PartialRatioStrategyT.cs +++ b/FuzzySharp/SimilarityRatio/Strategy/Generic/PartialRatioStrategyT.cs @@ -8,6 +8,9 @@ namespace Raffinert.FuzzySharp.SimilarityRatio.Strategy.Generic; internal static class PartialRatioStrategy where T : IEquatable { + // For tiny patterns, a few direct comparisons cost less than another vector. + private const int DirectEdgeScanMaxLength = 8; + /// /// Searches for the optimal alignment of the shorter span in the longer span /// and returns the partial fuzz.ratio for that alignment, as a value in [0…100]. @@ -99,7 +102,7 @@ private static ScoreAlignment PartialRatioImpl( throw new ArgumentException("Requires s1.Length <= s2.Length"); using var patternMatchVector = PatternMatchVector.Create(s1); - return PartialRatioImpl(patternMatchVector, s2, cutoff); + return PartialRatioImpl(patternMatchVector, s1, s2, cutoff); } /// @@ -108,6 +111,7 @@ private static ScoreAlignment PartialRatioImpl( /// [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ScoreAlignment PartialRatioImpl(IPatternMatchVector s1Vector, + ReadOnlySpan s1, ReadOnlySpan s2, double cutoff = 0.0) { @@ -121,6 +125,11 @@ private static ScoreAlignment PartialRatioImpl(IPatternMatchVector s1Vector, if (len1 == 0 || len2 == 0) return res; + // Equal-width inputs with disjoint alphabets have no matching edge. + // Keep this check bounded by the pattern length for long-text searches. + if (len1 == len2 && !ContainsAnyMatch(s1Vector, s2)) + return res; + if (len2 > len1) { int maximum = len1 + len1; @@ -214,42 +223,163 @@ private static ScoreAlignment PartialRatioImpl(IPatternMatchVector s1Vector, } } - // 1) Prefixes shorter than len1 - for (int i = 1; i < len1; i++) + if (len1 <= DirectEdgeScanMaxLength) + return ScanEdgesDirect(s1Vector, s2, cutoff, res); + + // Prefixes share the same LCS row: extend it once per character. + var prefix = ScanEdge(s1Vector, s2[..(len1 - 1)], reverse: false); + if (prefix.Score > res.Score && prefix.Score >= cutoff) + { + res.Score = cutoff = prefix.Score; + res.DestStart = 0; + res.DestEnd = prefix.Length; + } + + // Reversing both sequences preserves LCS. Scan suffixes shortest-first, + // retaining the longest on ties to preserve the original alignment order. + var tail = s2[(len2 - len1)..]; + if (!ContainsAnyMatch(s1Vector, tail)) + { + res.Score *= 100.0; + return res; + } + + (double Score, int Length) suffix; + if (len1 <= 64) + { + // All forward work is complete. Reuse the owned vector for the + // reversed suffix instead of allocating and populating another one. + PatternMatchVector.ReverseSingleWord(s1Vector); + suffix = ScanEdge(s1Vector, tail, reverse: true); + } + else + { + using var reversedVector = PatternMatchVector.CreateReversed(s1); + suffix = ScanEdge(reversedVector, tail, reverse: true); + } + if (suffix.Score > res.Score && suffix.Score >= cutoff) + { + res.Score = suffix.Score; + res.DestStart = len2 - suffix.Length; + res.DestEnd = len2; + } + + res.Score *= 100.0; + + return res; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool ContainsAnyMatch(IPatternMatchVector vector, ReadOnlySpan text) + { + foreach (var symbol in text) + if (vector.ContainsKey(symbol)) + return true; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static ScoreAlignment ScanEdgesDirect(IPatternMatchVector vector, + ReadOnlySpan text, double cutoff, ScoreAlignment result) + { + for (int length = 1; length < vector.Length; length++) { - if (!s1Vector.ContainsKey(s2[i - 1])) continue; - var slice = s2[..i]; - double sim = Indel.BlockNormalizedSimilarity(s1Vector, slice); - if (sim > res.Score && sim >= cutoff) + if (!vector.ContainsKey(text[length - 1])) continue; + double score = Indel.BlockNormalizedSimilarity(vector, text[..length]); + if (score > result.Score && score >= cutoff) { - res.Score = sim; - cutoff = sim; - res.DestStart = 0; - res.DestEnd = i; - if (sim == 1.0) { res.Score = 100.0; return res; } + result.Score = cutoff = score; + result.DestStart = 0; + result.DestEnd = length; } } - // 2) Suffixes up to len1 (includes the last full-width window) - for (int i = len2 - len1; i < len2; i++) + // Longest suffix first, preserving the existing tie order. + for (int start = text.Length - vector.Length; start < text.Length; start++) { - if (!s1Vector.ContainsKey(s2[i])) continue; - var tail = s2[i..]; - double sim = Indel.BlockNormalizedSimilarity(s1Vector, tail); - if (sim > res.Score && sim >= cutoff) + if (!vector.ContainsKey(text[start])) continue; + double score = Indel.BlockNormalizedSimilarity(vector, text[start..]); + if (score > result.Score && score >= cutoff) { - res.Score = sim; - cutoff = sim; - res.DestStart = i; - res.DestEnd = len2; - if (sim == 1.0) { res.Score = 100.0; return res; } + result.Score = score; + result.DestStart = start; + result.DestEnd = text.Length; + if (score == 1.0) break; + } + } + result.Score *= 100.0; + return result; + } + + // The state after k symbols also represents the LCS for the next + // prefix after one additional bit-parallel update. + private static (double Score, int Length) ScanEdge( + IPatternMatchVector vector, ReadOnlySpan text, bool reverse) + { + int m = vector.Length; + double best = 0; + int bestLength = 0; + if (m <= 64) + { + ulong state = m == 64 ? ulong.MaxValue : (1UL << m) - 1; + for (int i = 0; i < text.Length; i++) + { + T symbol = text[reverse ? text.Length - i - 1 : i]; + ulong matches = vector.GetOrZero(symbol)[0]; + if (matches == 0) + continue; // An unmatched extension cannot improve the ratio. + + ulong u = state & matches; + state = unchecked((state + u) | (state - u)); + OfferEdge(LongestCommonSubsequence.CountZeroBits(state, m), m, i + 1, + reverse, ref best, ref bestLength); } + return (best, bestLength); } - res.Score *= 100.0; + int blocks = vector.Blocks; + var maskLookup = (IPatternMatchVectorImpl)vector; + ulong[] rented = blocks > 16 ? ArrayPool.Shared.Rent(blocks) : null; + Span row = rented == null ? stackalloc ulong[blocks] : rented.AsSpan(0, blocks); + try + { + row.Fill(ulong.MaxValue); + int tail = m & 63; + if (tail != 0) + row[blocks - 1] = (1UL << tail) - 1; - return res; + for (int i = 0; i < text.Length; i++) + { + T symbol = text[reverse ? text.Length - i - 1 : i]; + if (!maskLookup.TryGetMask(symbol, out var matches)) + continue; + + LongestCommonSubsequence.AdvanceMultiWordRow(row, matches); + OfferEdge(LongestCommonSubsequence.CountZeroBits(row, m), m, i + 1, + reverse, ref best, ref bestLength); + } + return (best, bestLength); + } + finally + { + if (rented != null) + ArrayPool.Shared.Return(rented); + } + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void OfferEdge(int lcs, int patternLength, int length, bool preferLongest, + ref double best, ref int bestLength) + { + int maximum = patternLength + length; + // Same floating-point expression as BlockNormalizedSimilarity. + double score = 1.0 - (maximum - 2 * lcs) / (double)maximum; + if (score > best || (preferLongest && score == best && score > 0)) + { + best = score; + bestLength = length; + } } internal record struct ScoreAlignment(double Score, int SrcStart, int SrcEnd, int DestStart, int DestEnd); diff --git a/FuzzySharp/Utils/PatternMatchVector.cs b/FuzzySharp/Utils/PatternMatchVector.cs index 92cf700..06f45e0 100644 --- a/FuzzySharp/Utils/PatternMatchVector.cs +++ b/FuzzySharp/Utils/PatternMatchVector.cs @@ -15,23 +15,43 @@ public interface IPatternMatchVector : IDisposable where TKey : notnull internal interface IPatternMatchVectorImpl : IPatternMatchVector where TKey : IEquatable { + bool TryGetMask(TKey key, out ReadOnlySpan mask); void Populate(ReadOnlySpan source); + void PopulateReversed(ReadOnlySpan source); + void ReverseSingleWord(); } public sealed class PatternMatchVector { public static IPatternMatchVector Create(ReadOnlySpan source) where T : notnull, IEquatable { - var blocks = (source.Length + 63) >> 6; - - var pmv = typeof(T) == typeof(char) - ? (IPatternMatchVectorImpl)(object)new PatternMatchVectorChar(source.Length, estimatedNonAsciiCharCount: 8, blocks: blocks) - : new PatternMatchVector(source.Length, 64, blocks); - + var pmv = CreateEmpty(source.Length); pmv.Populate(source); + return pmv; + } + internal static IPatternMatchVector CreateReversed(ReadOnlySpan source) where T : notnull, IEquatable + { + var pmv = CreateEmpty(source.Length); + pmv.PopulateReversed(source); return pmv; } + + internal static void ReverseSingleWord(IPatternMatchVector vector) where T : notnull, IEquatable + { + if (vector.Blocks != 1) + throw new ArgumentException("Requires a single-word pattern vector", nameof(vector)); + ((IPatternMatchVectorImpl)vector).ReverseSingleWord(); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static IPatternMatchVectorImpl CreateEmpty(int length) where T : notnull, IEquatable + { + var blocks = (length + 63) >> 6; + return typeof(T) == typeof(char) + ? (IPatternMatchVectorImpl)(object)new PatternMatchVectorChar(length, estimatedNonAsciiCharCount: 8, blocks: blocks) + : new PatternMatchVector(length, 64, blocks); + } } internal sealed class PatternMatchVector : IPatternMatchVectorImpl where T : notnull, IEquatable @@ -70,6 +90,22 @@ public void Populate(ReadOnlySpan source) } } + public void PopulateReversed(ReadOnlySpan source) + { + if (_disposed) throw new ObjectDisposedException(nameof(PatternMatchVector)); + + for (var position = 0; position < source.Length; position++) + AddBit(source[source.Length - position - 1], position); + } + + public void ReverseSingleWord() + { + if (_disposed) throw new ObjectDisposedException(nameof(PatternMatchVector)); + + for (int i = 0; i < _next; i++) + _buffer[i] = Polyfill.ReverseBits(_buffer[i]) >> (64 - Length); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] private void AddBit(T key, int position) { diff --git a/FuzzySharp/Utils/PatternMatchVectorChar.cs b/FuzzySharp/Utils/PatternMatchVectorChar.cs index 26b1d84..42b938c 100644 --- a/FuzzySharp/Utils/PatternMatchVectorChar.cs +++ b/FuzzySharp/Utils/PatternMatchVectorChar.cs @@ -95,6 +95,51 @@ public void Populate(ReadOnlySpan source) } } + public void PopulateReversed(ReadOnlySpan source) + { + if (_disposed) throw new ObjectDisposedException(nameof(PatternMatchVectorChar)); + + for (var block = 0; block < _blocks; block++) + { + var blockStart = block << 6; + var blockLength = Math.Min(64, source.Length - blockStart); + for (var offset = 0; offset < blockLength; offset++) + { + var key = source[source.Length - blockStart - offset - 1]; + var bit = 1UL << offset; + if (key <= 255u) + { + _fixedData[_asciiMasksOffset + (key * _blocks) + block] |= bit; + _fixedData[_asciiPresenceOffset + (key >> 6)] |= 1UL << (key & 63); + } + else + { + AddNonAsciiBit(key, block, bit); + } + } + } + } + + public void ReverseSingleWord() + { + if (_disposed) throw new ObjectDisposedException(nameof(PatternMatchVectorChar)); + + for (int word = 0; word < 4; word++) + { + ulong presence = _fixedData[_asciiPresenceOffset + word]; + while (presence != 0) + { + ulong lowest = presence & unchecked(0UL - presence); + int key = (word << 6) + Polyfill.PopCount(lowest - 1); + _fixedData[key] = Polyfill.ReverseBits(_fixedData[key]) >> (64 - Length); + presence &= presence - 1; + } + } + + for (int i = 0; i < _next; i++) + _buffer[i] = Polyfill.ReverseBits(_buffer[i]) >> (64 - Length); + } + private void PopulateSingleBlock(ReadOnlySpan source) { for (var position = 0; position < source.Length; position++) diff --git a/FuzzySharp/Utils/Polyfill.cs b/FuzzySharp/Utils/Polyfill.cs index e3fd0f9..9237d2b 100644 --- a/FuzzySharp/Utils/Polyfill.cs +++ b/FuzzySharp/Utils/Polyfill.cs @@ -5,6 +5,15 @@ namespace Raffinert.FuzzySharp.Utils; internal static class Polyfill { + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static ulong ReverseBits(ulong value) + { + value = ((value >> 1) & 0x5555555555555555UL) | ((value & 0x5555555555555555UL) << 1); + value = ((value >> 2) & 0x3333333333333333UL) | ((value & 0x3333333333333333UL) << 2); + value = ((value >> 4) & 0x0F0F0F0F0F0F0F0FUL) | ((value & 0x0F0F0F0F0F0F0F0FUL) << 4); + return System.Buffers.Binary.BinaryPrimitives.ReverseEndianness(value); + } + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int PopCount(ulong value) { @@ -40,4 +49,4 @@ public static void ArrayFill(T[] array, T value, int startIndex, int count) } #endif } -} \ No newline at end of file +} diff --git a/README.md b/README.md index f6f9cb8..045d8ed 100644 --- a/README.md +++ b/README.md @@ -504,19 +504,32 @@ Fuzz.Ratio("new york mets", "NEW YORK METS", StringPreprocessor.Full); ## Performance -The distance implementations use bit-parallel algorithms designed to reduce both execution time and allocations. The table below compares naive DP Levenshtein distance calculation (baseline), original FuzzySharp, Fastenshtein, Quickenshtein, and Raffinert.FuzzySharp. - -Random words of 3 to 1024 random chars (`LevenshteinLarge.cs`): - -| Method | Mean | Error | StdDev | Ratio | RatioSD | Gen0 | Gen1 | Allocated | Alloc Ratio | -|-----------------------------------------------------------------|------------|------------|-----------|-------|---------|------------|------------|-------------|-------------| -| NaiveDp | 231.563 ms | 57.5403 ms | 3.1540 ms | 1.00 | 0.02 | 43500.0000 | 34500.0000 | 275312920 B | 1.000 | -| [FuzzySharp](https://github.com/JakeBayer/FuzzySharp) | 141.820 ms | 4.0905 ms | 0.2242 ms | 0.61 | 0.01 | - | - | 1545732 B | 0.006 | -| [Fastenshtein](https://github.com/DanHarltey/Fastenshtein) | 123.356 ms | 13.0959 ms | 0.7178 ms | 0.53 | 0.01 | - | - | 34028 B | 0.000 | -| [Quickenshtein](https://github.com/Turnerj/Quickenshtein) | 12.918 ms | 12.8046 ms | 0.7019 ms | 0.06 | 0.00 | - | - | 12 B | 0.000 | -| [Raffinert.FuzzySharp](https://github.com/Raffinert/FuzzySharp) | 4.970 ms | 0.3311 ms | 0.0181 ms | 0.02 | 0.00 | - | - | 3051 B | 0.000 | - -Benchmark sources are in [FuzzySharp.Benchmarks](FuzzySharp.Benchmarks). +Measured on **2026-11-28** using a development build of Raffinert.FuzzySharp and the original [FuzzySharp 2.0.2](https://github.com/JakeBayer/FuzzySharp) package. BenchmarkDotNet 0.15.8, Release, .NET 10.0.15 / SDK 11.0.100, Windows 11, Intel Core Ultra 9 275HX; sequential workloads pinned to P-core 10, tiered compilation and dynamic PGO disabled, two launches, six warmups and ten measured iterations per launch with a 300 ms target. No outliers were removed. Times below are means; `±` is the 99.9% confidence-interval half-width. Absolute times from earlier runs with different JIT or affinity settings are not a regression baseline. + +Selected fixed-input API comparisons (mean time per operation): + +| Operation | Measured build | Classic 2.0.2 | Speedup | +| --- | ---: | ---: | ---: | +| Ratio | 55.47 ± 0.54 ns | 174.65 ± 1.79 ns | 3.15× | +| PartialRatio | 246.00 ± 2.14 ns | 613.00 ± 8.36 ns | 2.49× | +| TokenSetRatio | 325.20 ± 3.70 ns | 2,017.90 ± 6.99 ns | 6.21× | +| WeightedRatio | 3,125.00 ± 47.00 ns | 8,984.00 ± 25.30 ns | 2.87× | +| PartialRatio (17-character pattern in 517-character text) | 1,051.00 ± 6.40 ns | 10,976.00 ± 48.70 ns | 10.44× | +| PartialRatio (257-character Cyrillic strings) | 13.220 ± 0.075 μs | 5,436.591 ± 37.149 μs | 411.24× | +| ExtractOne | 5.449 ± 0.019 μs | 19.320 ± 0.253 μs | 3.55× | +| ExtractAll | 5.633 ± 0.016 μs | 19.372 ± 0.176 μs | 3.44× | + +The large Levenshtein workload generates 20 seeded words with lengths in `[3, 1024)` and computes 400 ordered pairs per operation. Fastenshtein and Raffinert.FuzzySharp reuse an instance per source word. The `FuzzySharp` row below is Classic 2.0.2; ratios are relative to naive DP. Times and allocations are per batch: + +| Method | Mean | Error | StdDev | Ratio | Gen0 | Gen1 | Allocated | Alloc Ratio | +|--------------------- |-----------:|----------:|----------:|------:|-----------:|-----------:|------------:|------------:| +| NaiveDp | 146.787 ms | 1.2307 ms | 1.4173 ms | 1.00 | 14500.0000 | 12500.0000 | 275312720 B | 1.000 | +| [FuzzySharp](https://github.com/JakeBayer/FuzzySharp) | 105.555 ms | 0.0896 ms | 0.1032 ms | 0.72 | - | - | 1545632 B | 0.006 | +| [Fastenshtein](https://github.com/DanHarltey/Fastenshtein) | 97.087 ms | 0.4391 ms | 0.5056 ms | 0.66 | - | - | 33928 B | 0.000 | +| [Quickenshtein](https://github.com/Turnerj/Quickenshtein) | 8.226 ms | 0.0315 ms | 0.0363 ms | 0.06 | - | - | - | 0.000 | +| [Raffinert.FuzzySharp](https://github.com/Raffinert/FuzzySharp) | 2.399 ms | 0.0065 ms | 0.0075 ms | 0.02 | - | - | 2080 B | 0.000 | + +See [benchmark results and reproduction instructions](https://github.com/Raffinert/FuzzySharp/blob/master/FuzzySharp.Benchmarks/README.md) for cache/parallel variants, multiword cases, allocations and inputs. These microbenchmarks cover specific inputs on one machine; small differences need longer measurements. Partial-ratio algorithms and score rounding differ between the libraries. ## Migration Notes