Skip to content

Commit cbb949d

Browse files
committed
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.
1 parent eaa698d commit cbb949d

5 files changed

Lines changed: 71 additions & 50 deletions

File tree

‎LibGit2Sharp/ContentChanges.cs‎

Lines changed: 10 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -89,44 +89,37 @@ private unsafe int FileCallback(git_diff_delta* delta, float progress, IntPtr pa
8989
return 0;
9090
}
9191

92-
private unsafe int HunkCallback(git_diff_delta* delta, GitDiffHunk hunk, IntPtr payload)
92+
private unsafe int HunkCallback(git_diff_delta* delta, git_diff_hunk* hunk, IntPtr payload)
9393
{
94-
string decodedContent = LaxUtf8Marshaler.FromBuffer(hunk.Header, (int)hunk.HeaderLen);
94+
string decodedContent = LaxUtf8Marshaler.FromNative((IntPtr)hunk->Header, (int)hunk->HeaderLen);
9595

9696
AppendToPatch(decodedContent);
9797
return 0;
9898
}
9999

100-
private unsafe int LineCallback(git_diff_delta* delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload)
100+
private unsafe int LineCallback(git_diff_delta* delta, git_diff_hunk* hunk, git_diff_line* line, IntPtr payload)
101101
{
102-
string decodedContent = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen);
102+
string decodedContent = LaxUtf8Marshaler.FromNative(line->content, (int)line->contentLen);
103103

104-
string prefix;
105-
106-
switch (line.lineOrigin)
104+
switch (line->lineOrigin)
107105
{
108106
case GitDiffLineOrigin.GIT_DIFF_LINE_ADDITION:
109-
AddedLines.Add(new Line(line.NewLineNo, decodedContent));
107+
AddedLines.Add(new Line(line->NewLineNo, decodedContent));
110108
LinesAdded++;
111-
prefix = Encoding.ASCII.GetString(new[] { (byte)line.lineOrigin });
109+
AppendToPatch("+");
112110
break;
113111

114112
case GitDiffLineOrigin.GIT_DIFF_LINE_DELETION:
115-
DeletedLines.Add(new Line(line.OldLineNo, decodedContent));
113+
DeletedLines.Add(new Line(line->OldLineNo, decodedContent));
116114
LinesDeleted++;
117-
prefix = Encoding.ASCII.GetString(new[] { (byte)line.lineOrigin });
115+
AppendToPatch("-");
118116
break;
119117

120118
case GitDiffLineOrigin.GIT_DIFF_LINE_CONTEXT:
121-
prefix = Encoding.ASCII.GetString(new[] { (byte)line.lineOrigin });
122-
break;
123-
124-
default:
125-
prefix = string.Empty;
119+
AppendToPatch(" ");
126120
break;
127121
}
128122

129-
AppendToPatch(prefix);
130123
AppendToPatch(decodedContent);
131124
return 0;
132125
}

‎LibGit2Sharp/Core/GitDiff.cs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -273,20 +273,20 @@ internal unsafe struct git_diff_delta
273273
}
274274

275275
[StructLayout(LayoutKind.Sequential)]
276-
internal class GitDiffHunk
276+
internal unsafe struct git_diff_hunk
277277
{
278+
public const int HeaderSize = 128;
279+
278280
public int OldStart;
279281
public int OldLines;
280282
public int NewStart;
281283
public int NewLines;
282284
public UIntPtr HeaderLen;
283-
284-
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)]
285-
public byte[] Header;
285+
public fixed byte Header[HeaderSize];
286286
}
287287

288288
[StructLayout(LayoutKind.Sequential)]
289-
internal class GitDiffLine
289+
internal struct git_diff_line
290290
{
291291
public GitDiffLineOrigin lineOrigin;
292292
public int OldLineNo;

‎LibGit2Sharp/Core/NativeMethods.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -663,14 +663,14 @@ internal unsafe delegate int git_diff_file_cb(
663663
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
664664
internal unsafe delegate int git_diff_hunk_cb(
665665
[In] git_diff_delta* delta,
666-
[In] GitDiffHunk hunk,
666+
[In] git_diff_hunk* hunk,
667667
IntPtr payload);
668668

669669
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
670670
internal unsafe delegate int git_diff_line_cb(
671671
[In] git_diff_delta* delta,
672-
[In] GitDiffHunk hunk,
673-
[In] GitDiffLine line,
672+
[In] git_diff_hunk* hunk,
673+
[In] git_diff_line* line,
674674
IntPtr payload);
675675

676676
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]

‎LibGit2Sharp/ObjectId.cs‎

Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System;
22
using System.Globalization;
3-
using System.Linq;
43
using LibGit2Sharp.Core;
54

65
namespace LibGit2Sharp
@@ -100,6 +99,12 @@ public ObjectId(string sha)
10099
this.sha = sha;
101100
}
102101

102+
private ObjectId(GitOid oid, string sha)
103+
{
104+
this.oid = oid;
105+
this.sha = sha;
106+
}
107+
103108
internal GitOid Oid
104109
{
105110
get { return oid; }
@@ -129,9 +134,17 @@ public string Sha
129134
/// <returns>true if the <paramref name="sha"/> parameter was converted successfully; otherwise, false.</returns>
130135
public static bool TryParse(string sha, out ObjectId result)
131136
{
132-
result = BuildOidFrom(sha, false);
137+
GitOid? parsedOid = BuildOidFrom(sha, false);
133138

134-
return result != null;
139+
if (!parsedOid.HasValue)
140+
{
141+
result = null;
142+
return false;
143+
}
144+
145+
// A valid sha is already in canonical lowercase form, so reuse it rather than re-encoding the bytes.
146+
result = new ObjectId(parsedOid.Value, sha);
147+
return true;
135148
}
136149

137150
private static GitOid? BuildOidFrom(string sha, bool shouldThrowIfInvalid)
@@ -257,11 +270,16 @@ private static byte[] BuildReverseHexDigits()
257270
return bytes;
258271
}
259272

260-
internal static string ToString(byte[] id, int lengthInNibbles)
273+
internal static unsafe string ToString(byte[] id, int lengthInNibbles)
261274
{
262275
// Inspired from http://stackoverflow.com/questions/623104/c-byte-to-hex-string/3974535#3974535
263276

264-
var c = new char[lengthInNibbles];
277+
if ((uint)lengthInNibbles > HexSize)
278+
{
279+
throw new ArgumentOutOfRangeException(nameof(lengthInNibbles));
280+
}
281+
282+
char* c = stackalloc char[HexSize];
265283

266284
for (int i = 0; i < (lengthInNibbles & -2); i++)
267285
{
@@ -280,7 +298,7 @@ internal static string ToString(byte[] id, int lengthInNibbles)
280298
c[lengthInNibbles - 1] = hexDigits[b];
281299
}
282300

283-
return new string(c);
301+
return new string(c, 0, lengthInNibbles);
284302
}
285303

286304
private static GitOid ToOid(string sha)
@@ -330,7 +348,20 @@ private static bool LooksValid(string objectId, bool throwIfInvalid)
330348
nameof(objectId));
331349
}
332350

333-
return objectId.All(c => hexDigits.IndexOf(c) >= 0);
351+
foreach (char c in objectId)
352+
{
353+
if (!IsHexDigit(c))
354+
{
355+
return false;
356+
}
357+
}
358+
359+
return true;
360+
}
361+
362+
private static bool IsHexDigit(char c)
363+
{
364+
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
334365
}
335366

336367
/// <summary>

‎LibGit2Sharp/Patch.cs‎

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ public class Patch : IEnumerable<PatchEntryChanges>, IDiffResult
2424
private int linesAdded;
2525
private int linesDeleted;
2626

27+
// The entry git_patch_print is currently printing. Every line of a patch belongs
28+
// to the delta added just before printing it, so there is no need to decode the
29+
// path and look the entry up for each line.
30+
private PatchEntryChanges currentChange;
31+
2732
/// <summary>
2833
/// Needed for mocking purposes.
2934
/// </summary>
@@ -51,24 +56,17 @@ private unsafe void AddFileChange(git_diff_delta* delta)
5156
{
5257
var treeEntryChanges = new TreeEntryChanges(delta);
5358

54-
changes.Add(treeEntryChanges.Path, new PatchEntryChanges(delta->flags.HasFlag(GitDiffFlags.GIT_DIFF_FLAG_BINARY), treeEntryChanges));
59+
currentChange = new PatchEntryChanges(delta->flags.HasFlag(GitDiffFlags.GIT_DIFF_FLAG_BINARY), treeEntryChanges);
60+
changes.Add(treeEntryChanges.Path, currentChange);
5561
}
5662

57-
private unsafe int PrintCallBack(git_diff_delta* delta, GitDiffHunk hunk, GitDiffLine line, IntPtr payload)
63+
private unsafe int PrintCallBack(git_diff_delta* delta, git_diff_hunk* hunk, git_diff_line* line, IntPtr payload)
5864
{
59-
string patchPart = LaxUtf8Marshaler.FromNative(line.content, (int)line.contentLen);
60-
61-
// Deleted files mean no "new file" path
65+
string patchPart = LaxUtf8Marshaler.FromNative(line->content, (int)line->contentLen);
6266

63-
var pathPtr = delta->new_file.Path != null
64-
? delta->new_file.Path
65-
: delta->old_file.Path;
66-
var filePath = LaxFilePathMarshaler.FromNative(pathPtr);
67-
68-
PatchEntryChanges currentChange = this[filePath];
6967
string prefix = string.Empty;
7068

71-
switch (line.lineOrigin)
69+
switch (line->lineOrigin)
7270
{
7371
case GitDiffLineOrigin.GIT_DIFF_LINE_CONTEXT:
7472
prefix = " ";
@@ -77,22 +75,21 @@ private unsafe int PrintCallBack(git_diff_delta* delta, GitDiffHunk hunk, GitDif
7775
case GitDiffLineOrigin.GIT_DIFF_LINE_ADDITION:
7876
linesAdded++;
7977
currentChange.LinesAdded++;
80-
currentChange.AddedLines.Add(new Line(line.NewLineNo, patchPart));
78+
currentChange.AddedLines.Add(new Line(line->NewLineNo, patchPart));
8179
prefix = "+";
8280
break;
8381

8482
case GitDiffLineOrigin.GIT_DIFF_LINE_DELETION:
8583
linesDeleted++;
8684
currentChange.LinesDeleted++;
87-
currentChange.DeletedLines.Add(new Line(line.OldLineNo, patchPart));
85+
currentChange.DeletedLines.Add(new Line(line->OldLineNo, patchPart));
8886
prefix = "-";
8987
break;
9088
}
9189

92-
string formattedOutput = string.Concat(prefix, patchPart);
93-
94-
fullPatchBuilder.Append(formattedOutput);
95-
currentChange.AppendToPatch(formattedOutput);
90+
fullPatchBuilder.Append(prefix).Append(patchPart);
91+
currentChange.AppendToPatch(prefix);
92+
currentChange.AppendToPatch(patchPart);
9693

9794
return 0;
9895
}

0 commit comments

Comments
 (0)