Skip to content

Improve Performance of repo.Commits.QueryBy(<filepath>) #1706

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions LibGit2Sharp/Core/FileHistory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ private static void DetermineParentPaths(IRepository repo, Commit currentCommit,

private static string ParentPath(IRepository repo, Commit currentCommit, string currentPath, Commit parentCommit)
{
// optimization: if the SHA of the parent commit's TreeEntry is the same as this commit's TreeEntry then
// they are the same and there is no need to diff the commit
TreeEntry parentTreeEntry = parentCommit.Tree[currentPath];
TreeEntry thisTreeEntry = currentCommit.Tree[currentPath];
if (parentTreeEntry != null && parentTreeEntry.Target.Sha == thisTreeEntry.Target.Sha)
{
return currentPath;
}

// something in the tree is different, so we need to diff the commits to look for renames
using (var treeChanges = repo.Diff.Compare<TreeChanges>(parentCommit.Tree, currentCommit.Tree))
{
var treeEntryChanges = treeChanges.FirstOrDefault(c => c.Path == currentPath);
Expand Down
14 changes: 13 additions & 1 deletion LibGit2Sharp/Tree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ internal Tree(Repository repo, ObjectId id, string path)
/// <exception cref="NotFoundException">Throws if tree is missing</exception>
public virtual int Count => lazyCount.Value;

private Dictionary<string, TreeEntry> _treeCache;

/// <summary>
/// Gets the <see cref="TreeEntry"/> pointed at by the <paramref name="relativePath"/> in this <see cref="Tree"/> instance.
/// </summary>
Expand All @@ -51,9 +53,19 @@ internal Tree(Repository repo, ObjectId id, string path)
/// <exception cref="NotFoundException">Throws if tree is missing</exception>
public virtual TreeEntry this[string relativePath]
{
get { return RetrieveFromPath(relativePath); }
get
{
TreeEntry ret;
if (_treeCache == null) _treeCache = new Dictionary<string, TreeEntry>();
else if (_treeCache.TryGetValue(relativePath, out ret)) return ret;

ret = RetrieveFromPath(relativePath);
_treeCache[relativePath] = ret;
return ret;
}
}


private unsafe TreeEntry RetrieveFromPath(string relativePath)
{
if (string.IsNullOrEmpty(relativePath))
Expand Down