Skip to content

Commit 1adcff1

Browse files
committed
Reduce the number of reallocations
1 parent 1238c81 commit 1adcff1

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

LibGit2Sharp/Core/GitBufWriteStream.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using System;
22
using System.IO;
3+
using LibGit2Sharp.Core.Handles;
34

45
namespace LibGit2Sharp.Core
56
{
@@ -10,6 +11,9 @@ internal class GitBufWriteStream : Stream
1011
internal GitBufWriteStream(IntPtr gitBufPointer)
1112
{
1213
this.gitBufPointer = gitBufPointer;
14+
15+
//Preallocate the buffer
16+
Proxy.git_buf_grow(gitBufPointer, 1024);
1317
}
1418

1519
public override void Flush()
@@ -33,9 +37,31 @@ public override int Read(byte[] buffer, int offset, int count)
3337

3438
public override void Write(byte[] buffer, int offset, int count)
3539
{
40+
AutoGrowBuffer(count);
41+
3642
Proxy.git_buf_put(gitBufPointer, buffer, offset, count);
3743
}
3844

45+
private void AutoGrowBuffer(int count)
46+
{
47+
var gitBuf = gitBufPointer.MarshalAs<GitBuf>();
48+
49+
var asize = (uint)gitBuf.asize;
50+
var size = (uint)gitBuf.size;
51+
52+
var isBufferLargeEnoughToHoldTheNewData = (asize - size) > count;
53+
var filledBufferPercentage = (100.0 * size / asize);
54+
55+
if (isBufferLargeEnoughToHoldTheNewData && filledBufferPercentage < 90)
56+
{
57+
return;
58+
}
59+
60+
var targetSize = (uint)(1.5 * (asize + count));
61+
62+
Proxy.git_buf_grow(gitBufPointer, targetSize);
63+
}
64+
3965
public override bool CanRead
4066
{
4167
get { return false; }

0 commit comments

Comments
 (0)