Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
64 changes: 64 additions & 0 deletions FuzzySharp.Benchmarks/Compare-Performance.ps1
Original file line number Diff line number Diff line change
@@ -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"
12 changes: 12 additions & 0 deletions FuzzySharp.Benchmarks/FuzzySharp.Benchmarks.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@
<ProjectReference Include="..\FuzzySharp\FuzzySharp.csproj" />
</ItemGroup>

<!-- Compare-Performance.ps1 sets this environment property for this build
and the child project generated by BenchmarkDotNet. -->
<PropertyGroup Condition="'$(FuzzySharpPerformanceBaseline)' != ''">
<DefineConstants>$(DefineConstants);FUZZYSHARP_PERFORMANCE_BASELINE</DefineConstants>
</PropertyGroup>
<ItemGroup Condition="'$(FuzzySharpPerformanceBaseline)' != ''">
<Reference Include="FuzzySharp.PerformanceBaseline">
<HintPath>$(FuzzySharpPerformanceBaseline)</HintPath>
<Aliases>baseline</Aliases>
</Reference>
</ItemGroup>

<ItemGroup>
<Folder Include="BenchmarkDotNet.Artifacts\results\" />
</ItemGroup>
Expand Down
34 changes: 34 additions & 0 deletions FuzzySharp.Benchmarks/PartialRatioMultiwordBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -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);
}
154 changes: 154 additions & 0 deletions FuzzySharp.Benchmarks/PerformanceRegressionBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -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<char>(_first, _second);
#if FUZZYSHARP_PERFORMANCE_BASELINE
[Benchmark(Baseline = true)] public int Before() => Baseline.LongestCommonSubsequence.Similarity<char>(_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<char>(_first, _second).Sim;
#if FUZZYSHARP_PERFORMANCE_BASELINE
[Benchmark(Baseline = true)] public int Before() => Baseline.LongestCommonSubsequence.Matrix<char>(_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}")))
};
}
Loading
Loading