Skip to content

Commit

Permalink
Merge pull request #719 from Sergio0694/dev/opportunistic-stackalloc
Browse files Browse the repository at this point in the history
Use stackalloc to marshal constant buffer if possible
  • Loading branch information
Sergio0694 authored Dec 15, 2023
2 parents 8c1a547 + eab0bfb commit 347ae52
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
11 changes: 9 additions & 2 deletions src/ComputeSharp.D2D1.WinUI/Extensions/ID2D1EffectExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ public static T GetConstantBuffer<T>(this ref ID2D1Effect d2D1Effect)
return default;
}

byte[] buffer = ArrayPool<byte>.Shared.Rent(constantBufferSize);
byte[]? bufferArray = null;

Span<byte> buffer = constantBufferSize <= 64
? stackalloc byte[64]
: bufferArray = ArrayPool<byte>.Shared.Rent(constantBufferSize);

fixed (byte* p = buffer)
{
Expand All @@ -49,7 +53,10 @@ public static T GetConstantBuffer<T>(this ref ID2D1Effect d2D1Effect)

T shader = T.CreateFromConstantBuffer(buffer);

ArrayPool<byte>.Shared.Return(buffer);
if (bufferArray is not null)
{
ArrayPool<byte>.Shared.Return(bufferArray);
}

return shader;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Buffers;
using ComputeSharp.D2D1.Descriptors;
using ComputeSharp.D2D1.Extensions;
Expand Down Expand Up @@ -37,7 +38,11 @@ public T GetConstantBuffer()

this.d2D1DrawInfoUpdateContext->GetConstantBufferSize(&constantBufferSize).Assert();

byte[] buffer = ArrayPool<byte>.Shared.Rent((int)constantBufferSize);
byte[]? bufferArray = null;

Span<byte> buffer = constantBufferSize <= 64
? stackalloc byte[64]
: bufferArray = ArrayPool<byte>.Shared.Rent((int)constantBufferSize);

fixed (byte* pBuffer = buffer)
{
Expand All @@ -46,7 +51,10 @@ public T GetConstantBuffer()

T shader = T.CreateFromConstantBuffer(buffer);

ArrayPool<byte>.Shared.Return(buffer);
if (bufferArray is not null)
{
ArrayPool<byte>.Shared.Return(bufferArray);
}

return shader;
}
Expand Down

0 comments on commit 347ae52

Please sign in to comment.