Skip to content

Commit 1572d6a

Browse files
committed
perf: Use ArrayPool<T> for Grid's CellCacheStackVector inner storage
1 parent 3db5555 commit 1572d6a

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/Uno.Foundation/Collections/StackVector.cs

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
using System.Collections;
33
using System.Collections.Generic;
44
using System.Diagnostics;
5+
using Uno.Buffers;
56

67
namespace Uno.Collections
78
{
@@ -10,10 +11,11 @@ internal class StackVector<T> : IEnumerable<T> where T : struct
1011
internal delegate bool RefPredicateDelegate(ref T item);
1112

1213
private Memory<T> _inner;
14+
private T[] _originalArray;
1315

1416
public StackVector(int capacity, int initialLength = 0)
1517
{
16-
_inner = new Memory<T>(new T[capacity]);
18+
AllocateInner(capacity);
1719
Count = initialLength;
1820
}
1921

@@ -34,15 +36,32 @@ public void Resize(int newCount)
3436
// list.
3537
// The resize takes place only to reuse the working
3638
// memory, not to store it.
37-
38-
_inner = new Memory<T>(new T[newCount]);
39+
AllocateInner(newCount);
3940

4041
IncrementResizeCount();
4142
}
4243

4344
Count = newCount;
4445
}
4546

47+
private void AllocateInner(int newSize)
48+
{
49+
if (_originalArray != null)
50+
{
51+
ArrayPool<T>.Shared.Return(_originalArray, clearArray: true);
52+
}
53+
54+
_inner = new Memory<T>(_originalArray = ArrayPool<T>.Shared.Rent(newSize));
55+
}
56+
57+
public void Dispose()
58+
{
59+
if (_originalArray != null)
60+
{
61+
ArrayPool<T>.Shared.Return(_originalArray, clearArray: true);
62+
}
63+
}
64+
4665
#if DEBUG
4766
internal int _numberOfResizes;
4867
internal static int _totalNumberOfResizes;

src/Uno.UI/UI/Xaml/Controls/Grid/Grid.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,9 @@ void MeasureCellsGroup(
444444

445445
// Cleanup
446446
// return hr;
447+
448+
// Return allocated memory to the pool
449+
spanStore.Dispose();
447450
}
448451

449452
// Measure a child of the Grid by taking in consideration the properties of
@@ -1324,6 +1327,9 @@ private XSIZEF InnerMeasureOverride(XSIZEF availableSize)
13241327

13251328
desiredSize.Width = GetDesiredInnerSize(m_pColumns) + combinedColumnSpacing;
13261329
desiredSize.Height = GetDesiredInnerSize(m_pRows) + combinedRowSpacing;
1330+
1331+
// Return memory to the array pool
1332+
cellCacheVector.Dispose();
13271333
}
13281334

13291335
desiredSize.Width += combinedThickness.Width;

0 commit comments

Comments
 (0)