From cbb949db9b317e511cf360e9dfb8c8cf54af57b1 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 26 Nov 2026 23:55:49 +1100 Subject: [PATCH 1/4] Reduce allocations in diff callbacks and ObjectId Diff hunk and line callbacks now receive pointers to blittable git_diff_hunk and git_diff_line structs. Previously every line marshaled two class instances plus a copy of the 128 byte hunk header. ContentChanges uses constant prefix strings instead of building one per line. Patch no longer concatenates the prefix and line into a new string, and keeps the entry being printed instead of decoding the file path and looking it up for every line. ObjectId builds its hex string from a stackalloc buffer, validates shas without LINQ, and TryParse reuses the parsed sha instead of re-encoding it. --- LibGit2Sharp/ContentChanges.cs | 27 +++++++----------- LibGit2Sharp/Core/GitDiff.cs | 10 +++---- LibGit2Sharp/Core/NativeMethods.cs | 6 ++-- LibGit2Sharp/ObjectId.cs | 45 +++++++++++++++++++++++++----- LibGit2Sharp/Patch.cs | 33 ++++++++++------------ 5 files changed, 71 insertions(+), 50 deletions(-) diff --git a/LibGit2Sharp/ContentChanges.cs b/LibGit2Sharp/ContentChanges.cs index c4628f919..9dce2fcf8 100644 --- a/LibGit2Sharp/ContentChanges.cs +++ b/LibGit2Sharp/ContentChanges.cs @@ -89,44 +89,37 @@ private unsafe int FileCallback(git_diff_delta* delta, float progress, IntPtr pa return 0; } - private unsafe int HunkCallback(git_diff_delta* delta, GitDiffHunk hunk, IntPtr payload) + private unsafe int HunkCallback(git_diff_delta* delta, git_diff_hunk* hunk, IntPtr payload) { - string decodedContent = LaxUtf8Marshaler.FromBuffer(hunk.Header, (int)hunk.HeaderLen); + string decodedContent = LaxUtf8Marshaler.FromNative((IntPtr)hunk->Header, (int)hunk->HeaderLen); AppendToPatch(decodedContent); return 0; } - private unsafe int LineCallback(git_diff_delta* delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload) + private unsafe int LineCallback(git_diff_delta* delta, git_diff_hunk* hunk, git_diff_line* line, IntPtr payload) { - string decodedContent = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen); + string decodedContent = LaxUtf8Marshaler.FromNative(line->content, (int)line->contentLen); - string prefix; - - switch (line.lineOrigin) + switch (line->lineOrigin) { case GitDiffLineOrigin.GIT_DIFF_LINE_ADDITION: - AddedLines.Add(new Line(line.NewLineNo, decodedContent)); + AddedLines.Add(new Line(line->NewLineNo, decodedContent)); LinesAdded++; - prefix = Encoding.ASCII.GetString(new[] { (byte)line.lineOrigin }); + AppendToPatch("+"); break; case GitDiffLineOrigin.GIT_DIFF_LINE_DELETION: - DeletedLines.Add(new Line(line.OldLineNo, decodedContent)); + DeletedLines.Add(new Line(line->OldLineNo, decodedContent)); LinesDeleted++; - prefix = Encoding.ASCII.GetString(new[] { (byte)line.lineOrigin }); + AppendToPatch("-"); break; case GitDiffLineOrigin.GIT_DIFF_LINE_CONTEXT: - prefix = Encoding.ASCII.GetString(new[] { (byte)line.lineOrigin }); - break; - - default: - prefix = string.Empty; + AppendToPatch(" "); break; } - AppendToPatch(prefix); AppendToPatch(decodedContent); return 0; } diff --git a/LibGit2Sharp/Core/GitDiff.cs b/LibGit2Sharp/Core/GitDiff.cs index 44679124d..1d1fc4702 100644 --- a/LibGit2Sharp/Core/GitDiff.cs +++ b/LibGit2Sharp/Core/GitDiff.cs @@ -273,20 +273,20 @@ internal unsafe struct git_diff_delta } [StructLayout(LayoutKind.Sequential)] - internal class GitDiffHunk + internal unsafe struct git_diff_hunk { + public const int HeaderSize = 128; + public int OldStart; public int OldLines; public int NewStart; public int NewLines; public UIntPtr HeaderLen; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)] - public byte[] Header; + public fixed byte Header[HeaderSize]; } [StructLayout(LayoutKind.Sequential)] - internal class GitDiffLine + internal struct git_diff_line { public GitDiffLineOrigin lineOrigin; public int OldLineNo; diff --git a/LibGit2Sharp/Core/NativeMethods.cs b/LibGit2Sharp/Core/NativeMethods.cs index cbb850b16..632f3c13d 100644 --- a/LibGit2Sharp/Core/NativeMethods.cs +++ b/LibGit2Sharp/Core/NativeMethods.cs @@ -663,14 +663,14 @@ internal unsafe delegate int git_diff_file_cb( [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int git_diff_hunk_cb( [In] git_diff_delta* delta, - [In] GitDiffHunk hunk, + [In] git_diff_hunk* hunk, IntPtr payload); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int git_diff_line_cb( [In] git_diff_delta* delta, - [In] GitDiffHunk hunk, - [In] GitDiffLine line, + [In] git_diff_hunk* hunk, + [In] git_diff_line* line, IntPtr payload); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] diff --git a/LibGit2Sharp/ObjectId.cs b/LibGit2Sharp/ObjectId.cs index d87bbcb34..b38b8586d 100644 --- a/LibGit2Sharp/ObjectId.cs +++ b/LibGit2Sharp/ObjectId.cs @@ -1,6 +1,5 @@ using System; using System.Globalization; -using System.Linq; using LibGit2Sharp.Core; namespace LibGit2Sharp @@ -100,6 +99,12 @@ public ObjectId(string sha) this.sha = sha; } + private ObjectId(GitOid oid, string sha) + { + this.oid = oid; + this.sha = sha; + } + internal GitOid Oid { get { return oid; } @@ -129,9 +134,17 @@ public string Sha /// true if the parameter was converted successfully; otherwise, false. public static bool TryParse(string sha, out ObjectId result) { - result = BuildOidFrom(sha, false); + GitOid? parsedOid = BuildOidFrom(sha, false); - return result != null; + if (!parsedOid.HasValue) + { + result = null; + return false; + } + + // A valid sha is already in canonical lowercase form, so reuse it rather than re-encoding the bytes. + result = new ObjectId(parsedOid.Value, sha); + return true; } private static GitOid? BuildOidFrom(string sha, bool shouldThrowIfInvalid) @@ -257,11 +270,16 @@ private static byte[] BuildReverseHexDigits() return bytes; } - internal static string ToString(byte[] id, int lengthInNibbles) + internal static unsafe string ToString(byte[] id, int lengthInNibbles) { // Inspired from http://stackoverflow.com/questions/623104/c-byte-to-hex-string/3974535#3974535 - var c = new char[lengthInNibbles]; + if ((uint)lengthInNibbles > HexSize) + { + throw new ArgumentOutOfRangeException(nameof(lengthInNibbles)); + } + + char* c = stackalloc char[HexSize]; for (int i = 0; i < (lengthInNibbles & -2); i++) { @@ -280,7 +298,7 @@ internal static string ToString(byte[] id, int lengthInNibbles) c[lengthInNibbles - 1] = hexDigits[b]; } - return new string(c); + return new string(c, 0, lengthInNibbles); } private static GitOid ToOid(string sha) @@ -330,7 +348,20 @@ private static bool LooksValid(string objectId, bool throwIfInvalid) nameof(objectId)); } - return objectId.All(c => hexDigits.IndexOf(c) >= 0); + foreach (char c in objectId) + { + if (!IsHexDigit(c)) + { + return false; + } + } + + return true; + } + + private static bool IsHexDigit(char c) + { + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); } /// diff --git a/LibGit2Sharp/Patch.cs b/LibGit2Sharp/Patch.cs index 50157eb32..a0ca010f4 100644 --- a/LibGit2Sharp/Patch.cs +++ b/LibGit2Sharp/Patch.cs @@ -24,6 +24,11 @@ public class Patch : IEnumerable, IDiffResult private int linesAdded; private int linesDeleted; + // The entry git_patch_print is currently printing. Every line of a patch belongs + // to the delta added just before printing it, so there is no need to decode the + // path and look the entry up for each line. + private PatchEntryChanges currentChange; + /// /// Needed for mocking purposes. /// @@ -51,24 +56,17 @@ private unsafe void AddFileChange(git_diff_delta* delta) { var treeEntryChanges = new TreeEntryChanges(delta); - changes.Add(treeEntryChanges.Path, new PatchEntryChanges(delta->flags.HasFlag(GitDiffFlags.GIT_DIFF_FLAG_BINARY), treeEntryChanges)); + currentChange = new PatchEntryChanges(delta->flags.HasFlag(GitDiffFlags.GIT_DIFF_FLAG_BINARY), treeEntryChanges); + changes.Add(treeEntryChanges.Path, currentChange); } - private unsafe int PrintCallBack(git_diff_delta* delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload) + private unsafe int PrintCallBack(git_diff_delta* delta, git_diff_hunk* hunk, git_diff_line* line, IntPtr payload) { - string patchPart = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen); - - // Deleted files mean no "new file" path + string patchPart = LaxUtf8Marshaler.FromNative(line->content, (int)line->contentLen); - var pathPtr = delta->new_file.Path != null - ? delta->new_file.Path - : delta->old_file.Path; - var filePath = LaxFilePathMarshaler.FromNative(pathPtr); - - PatchEntryChanges currentChange = this[filePath]; string prefix = string.Empty; - switch (line.lineOrigin) + switch (line->lineOrigin) { case GitDiffLineOrigin.GIT_DIFF_LINE_CONTEXT: prefix = " "; @@ -77,22 +75,21 @@ private unsafe int PrintCallBack(git_diff_delta* delta, GitDiffHunk hunk, GitDif case GitDiffLineOrigin.GIT_DIFF_LINE_ADDITION: linesAdded++; currentChange.LinesAdded++; - currentChange.AddedLines.Add(new Line(line.NewLineNo, patchPart)); + currentChange.AddedLines.Add(new Line(line->NewLineNo, patchPart)); prefix = "+"; break; case GitDiffLineOrigin.GIT_DIFF_LINE_DELETION: linesDeleted++; currentChange.LinesDeleted++; - currentChange.DeletedLines.Add(new Line(line.OldLineNo, patchPart)); + currentChange.DeletedLines.Add(new Line(line->OldLineNo, patchPart)); prefix = "-"; break; } - string formattedOutput = string.Concat(prefix, patchPart); - - fullPatchBuilder.Append(formattedOutput); - currentChange.AppendToPatch(formattedOutput); + fullPatchBuilder.Append(prefix).Append(patchPart); + currentChange.AppendToPatch(prefix); + currentChange.AppendToPatch(patchPart); return 0; } From e833025f9328979a0a21b19ce4e68b97f69011f9 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 26 Nov 2026 23:55:49 +1100 Subject: [PATCH 2/4] Add benchmark project LibGit2Sharp.Benchmarks uses BenchmarkDotNet to measure ObjectId construction, commit walks and diffs, reporting allocations for each. It targets net472 and net11.0, so CI now installs the .NET 11 SDK for the build and Windows/macOS test jobs. --- .github/workflows/ci.yml | 3 +- .../CommitWalkBenchmarks.cs | 49 +++++++++++++ LibGit2Sharp.Benchmarks/DiffBenchmarks.cs | 70 +++++++++++++++++++ .../LibGit2Sharp.Benchmarks.csproj | 19 +++++ LibGit2Sharp.Benchmarks/ObjectIdBenchmarks.cs | 32 +++++++++ LibGit2Sharp.Benchmarks/Program.cs | 12 ++++ LibGit2Sharp.Benchmarks/README.md | 19 +++++ LibGit2Sharp.Benchmarks/TempRepository.cs | 45 ++++++++++++ LibGit2Sharp.sln | 6 ++ 9 files changed, 254 insertions(+), 1 deletion(-) create mode 100644 LibGit2Sharp.Benchmarks/CommitWalkBenchmarks.cs create mode 100644 LibGit2Sharp.Benchmarks/DiffBenchmarks.cs create mode 100644 LibGit2Sharp.Benchmarks/LibGit2Sharp.Benchmarks.csproj create mode 100644 LibGit2Sharp.Benchmarks/ObjectIdBenchmarks.cs create mode 100644 LibGit2Sharp.Benchmarks/Program.cs create mode 100644 LibGit2Sharp.Benchmarks/README.md create mode 100644 LibGit2Sharp.Benchmarks/TempRepository.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7fae84681..ccfa18dfd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,7 +21,7 @@ jobs: - name: Install .NET SDK uses: actions/setup-dotnet@v4.0.0 with: - dotnet-version: 9.0.x + dotnet-version: 11.0.x - name: Build run: dotnet build LibGit2Sharp.sln --configuration Release - name: Upload packages @@ -62,6 +62,7 @@ jobs: uses: actions/setup-dotnet@v4.0.0 with: dotnet-version: | + 11.0.x 9.0.x 8.0.x - name: Run ${{ matrix.tfm }} tests diff --git a/LibGit2Sharp.Benchmarks/CommitWalkBenchmarks.cs b/LibGit2Sharp.Benchmarks/CommitWalkBenchmarks.cs new file mode 100644 index 000000000..f590b8d0e --- /dev/null +++ b/LibGit2Sharp.Benchmarks/CommitWalkBenchmarks.cs @@ -0,0 +1,49 @@ +using BenchmarkDotNet.Attributes; + +namespace LibGit2Sharp.Benchmarks +{ + /// + /// Every commit yielded by the walk builds an from native memory. + /// + [MemoryDiagnoser] + public class CommitWalkBenchmarks + { + TempRepository repo; + + [Params(1000)] + public int CommitCount { get; set; } + + [GlobalSetup] + public void Setup() + { + repo = new TempRepository(); + + for (var i = 0; i < CommitCount; i++) + { + repo.Commit("file.txt", i.ToString(), $"Commit {i}"); + } + } + + [GlobalCleanup] + public void Cleanup() + { + repo.Dispose(); + } + + [Benchmark] + public int WalkCommits() + { + var count = 0; + + foreach (var commit in repo.Repository.Commits) + { + if (commit.Id != null) + { + count++; + } + } + + return count; + } + } +} diff --git a/LibGit2Sharp.Benchmarks/DiffBenchmarks.cs b/LibGit2Sharp.Benchmarks/DiffBenchmarks.cs new file mode 100644 index 000000000..7db68bb8b --- /dev/null +++ b/LibGit2Sharp.Benchmarks/DiffBenchmarks.cs @@ -0,0 +1,70 @@ +using System.Text; +using BenchmarkDotNet.Attributes; + +namespace LibGit2Sharp.Benchmarks +{ + /// + /// Diffs two versions of a file where every other line changed, so the + /// per-line diff callbacks dominate. + /// + [MemoryDiagnoser] + public class DiffBenchmarks + { + TempRepository repo; + Commit oldCommit; + Commit newCommit; + Blob oldBlob; + Blob newBlob; + + [Params(10000)] + public int LineCount { get; set; } + + [GlobalSetup] + public void Setup() + { + repo = new TempRepository(); + oldCommit = repo.Commit("file.txt", BuildContent(false), "Old"); + newCommit = repo.Commit("file.txt", BuildContent(true), "New"); + oldBlob = (Blob)oldCommit["file.txt"].Target; + newBlob = (Blob)newCommit["file.txt"].Target; + } + + [GlobalCleanup] + public void Cleanup() + { + repo.Dispose(); + } + + string BuildContent(bool modified) + { + var builder = new StringBuilder(); + + for (var i = 0; i < LineCount; i++) + { + if (modified && i % 2 == 0) + { + builder.Append("Changed line ").Append(i).Append('\n'); + continue; + } + + builder.Append("Original line ").Append(i).Append('\n'); + } + + return builder.ToString(); + } + + [Benchmark] + public int PatchBetweenTrees() + { + var patch = repo.Repository.Diff.Compare(oldCommit.Tree, newCommit.Tree); + return patch.LinesAdded; + } + + [Benchmark] + public int ContentChangesBetweenBlobs() + { + var changes = repo.Repository.Diff.Compare(oldBlob, newBlob); + return changes.LinesAdded; + } + } +} diff --git a/LibGit2Sharp.Benchmarks/LibGit2Sharp.Benchmarks.csproj b/LibGit2Sharp.Benchmarks/LibGit2Sharp.Benchmarks.csproj new file mode 100644 index 000000000..6dd191fe8 --- /dev/null +++ b/LibGit2Sharp.Benchmarks/LibGit2Sharp.Benchmarks.csproj @@ -0,0 +1,19 @@ + + + + Exe + net472;net11.0 + 12.0 + false + true + + + + + + + + + + + diff --git a/LibGit2Sharp.Benchmarks/ObjectIdBenchmarks.cs b/LibGit2Sharp.Benchmarks/ObjectIdBenchmarks.cs new file mode 100644 index 000000000..1a4f547bc --- /dev/null +++ b/LibGit2Sharp.Benchmarks/ObjectIdBenchmarks.cs @@ -0,0 +1,32 @@ +using System.Linq; +using BenchmarkDotNet.Attributes; + +namespace LibGit2Sharp.Benchmarks +{ + [MemoryDiagnoser] + public class ObjectIdBenchmarks + { + const string sha = "8496071c1b46c854b31185ea97743be6a8774479"; + + readonly byte[] rawId = new ObjectId(sha).RawId.ToArray(); + + [Benchmark] + public ObjectId FromSha() + { + return new ObjectId(sha); + } + + [Benchmark] + public ObjectId TryParse() + { + ObjectId.TryParse(sha, out var id); + return id; + } + + [Benchmark] + public ObjectId FromRawId() + { + return new ObjectId(rawId); + } + } +} diff --git a/LibGit2Sharp.Benchmarks/Program.cs b/LibGit2Sharp.Benchmarks/Program.cs new file mode 100644 index 000000000..de13b4311 --- /dev/null +++ b/LibGit2Sharp.Benchmarks/Program.cs @@ -0,0 +1,12 @@ +using BenchmarkDotNet.Running; + +namespace LibGit2Sharp.Benchmarks +{ + public static class Program + { + public static void Main(string[] args) + { + BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); + } + } +} diff --git a/LibGit2Sharp.Benchmarks/README.md b/LibGit2Sharp.Benchmarks/README.md new file mode 100644 index 000000000..c48adb299 --- /dev/null +++ b/LibGit2Sharp.Benchmarks/README.md @@ -0,0 +1,19 @@ +# LibGit2Sharp.Benchmarks + +[BenchmarkDotNet](https://benchmarkdotnet.org/) benchmarks for LibGit2Sharp. Every benchmark reports allocations. + +The diff and commit walk benchmarks build a throwaway repository under the temp folder in their setup and delete it afterwards. + +Run all benchmarks on .NET 11: + +``` +dotnet run -c Release -f net11.0 --project LibGit2Sharp.Benchmarks -- --filter * +``` + +Run on .NET Framework (Windows only): + +``` +dotnet run -c Release -f net472 --project LibGit2Sharp.Benchmarks -- --filter * +``` + +Pick benchmarks with `--filter`, for example `--filter *Diff*`. For a quicker, less precise run, add `--job short`. diff --git a/LibGit2Sharp.Benchmarks/TempRepository.cs b/LibGit2Sharp.Benchmarks/TempRepository.cs new file mode 100644 index 000000000..9d53ede0c --- /dev/null +++ b/LibGit2Sharp.Benchmarks/TempRepository.cs @@ -0,0 +1,45 @@ +using System; +using System.IO; + +namespace LibGit2Sharp.Benchmarks +{ + /// + /// A throwaway repository on disk, deleted on dispose. + /// + sealed class TempRepository : IDisposable + { + static readonly Signature signature = new Signature("Benchmark", "benchmark@example.com", new DateTimeOffset(2024, 1, 1, 0, 0, 0, TimeSpan.Zero)); + + readonly string directory; + + public TempRepository() + { + directory = Path.Combine(Path.GetTempPath(), "LibGit2Sharp.Benchmarks", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(directory); + Repository.Init(directory); + Repository = new Repository(directory); + } + + public Repository Repository { get; } + + public Commit Commit(string fileName, string content, string message) + { + File.WriteAllText(Path.Combine(directory, fileName), content); + Commands.Stage(Repository, fileName); + return Repository.Commit(message, signature, signature); + } + + public void Dispose() + { + Repository.Dispose(); + + // libgit2 writes object files as read-only, which blocks Directory.Delete on Windows. + foreach (var file in Directory.EnumerateFiles(directory, "*", SearchOption.AllDirectories)) + { + File.SetAttributes(file, FileAttributes.Normal); + } + + Directory.Delete(directory, true); + } + } +} diff --git a/LibGit2Sharp.sln b/LibGit2Sharp.sln index e99eec26f..a0b97ac2c 100644 --- a/LibGit2Sharp.sln +++ b/LibGit2Sharp.sln @@ -19,6 +19,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NativeLibraryLoadTestApp.x8 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NativeLibraryLoadTestApp.x64", "NativeLibraryLoadTestApp\x64\NativeLibraryLoadTestApp.x64.csproj", "{5C55175D-6A1F-4C51-B791-BF7DD00124EE}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LibGit2Sharp.Benchmarks", "LibGit2Sharp.Benchmarks\LibGit2Sharp.Benchmarks.csproj", "{918C6DA8-750B-499D-8E65-225767BF8704}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -41,6 +43,10 @@ Global {5C55175D-6A1F-4C51-B791-BF7DD00124EE}.Debug|Any CPU.Build.0 = Debug|Any CPU {5C55175D-6A1F-4C51-B791-BF7DD00124EE}.Release|Any CPU.ActiveCfg = Release|Any CPU {5C55175D-6A1F-4C51-B791-BF7DD00124EE}.Release|Any CPU.Build.0 = Release|Any CPU + {918C6DA8-750B-499D-8E65-225767BF8704}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {918C6DA8-750B-499D-8E65-225767BF8704}.Debug|Any CPU.Build.0 = Debug|Any CPU + {918C6DA8-750B-499D-8E65-225767BF8704}.Release|Any CPU.ActiveCfg = Release|Any CPU + {918C6DA8-750B-499D-8E65-225767BF8704}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 9c06972c0b2977d05a8d4abbec07d53734a254af Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 26 Nov 2026 23:55:49 +1100 Subject: [PATCH 3/4] Ignore Rider .idea folder --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 32e17b4d0..77452df54 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ Thumbs.db *.ncb *.suo .vs/ +.idea/ *.sln.ide/ *.tlb *.tlh From ba1e9b7991ce0afdca6c3e630e01a3ebf2c9b26c Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 27 Nov 2026 00:20:37 +1100 Subject: [PATCH 4/4] Add commit lookup benchmark Looks up 1,000 commits by id, which passes each id to libgit2 as a ref GitOid. --- LibGit2Sharp.Benchmarks/LookupBenchmarks.cs | 53 +++++++++++++++++++++ LibGit2Sharp.Benchmarks/README.md | 2 +- 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 LibGit2Sharp.Benchmarks/LookupBenchmarks.cs diff --git a/LibGit2Sharp.Benchmarks/LookupBenchmarks.cs b/LibGit2Sharp.Benchmarks/LookupBenchmarks.cs new file mode 100644 index 000000000..7f7640419 --- /dev/null +++ b/LibGit2Sharp.Benchmarks/LookupBenchmarks.cs @@ -0,0 +1,53 @@ +using System.Linq; +using BenchmarkDotNet.Attributes; + +namespace LibGit2Sharp.Benchmarks +{ + /// + /// Every lookup passes the id to libgit2 as a ref GitOid. + /// + [MemoryDiagnoser] + public class LookupBenchmarks + { + TempRepository repo; + ObjectId[] ids; + + [Params(1000)] + public int CommitCount { get; set; } + + [GlobalSetup] + public void Setup() + { + repo = new TempRepository(); + + for (var i = 0; i < CommitCount; i++) + { + repo.Commit("file.txt", i.ToString(), $"Commit {i}"); + } + + ids = repo.Repository.Commits.Select(c => c.Id).ToArray(); + } + + [GlobalCleanup] + public void Cleanup() + { + repo.Dispose(); + } + + [Benchmark] + public int LookupCommits() + { + var count = 0; + + foreach (var id in ids) + { + if (repo.Repository.Lookup(id) != null) + { + count++; + } + } + + return count; + } + } +} diff --git a/LibGit2Sharp.Benchmarks/README.md b/LibGit2Sharp.Benchmarks/README.md index c48adb299..626d44f2c 100644 --- a/LibGit2Sharp.Benchmarks/README.md +++ b/LibGit2Sharp.Benchmarks/README.md @@ -2,7 +2,7 @@ [BenchmarkDotNet](https://benchmarkdotnet.org/) benchmarks for LibGit2Sharp. Every benchmark reports allocations. -The diff and commit walk benchmarks build a throwaway repository under the temp folder in their setup and delete it afterwards. +The diff, commit walk and lookup benchmarks build a throwaway repository under the temp folder in their setup and delete it afterwards. Run all benchmarks on .NET 11: