diff --git a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs
index 6443dc70..e60f27db 100644
--- a/src/ComputeSharp.Shaders/ShaderRunner{T}.cs
+++ b/src/ComputeSharp.Shaders/ShaderRunner{T}.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using ComputeSharp.Graphics;
using ComputeSharp.Graphics.Buffers.Abstract;
@@ -13,6 +14,32 @@ using PipelineState = ComputeSharp.Graphics.Commands.PipelineState;
namespace ComputeSharp.Shaders
{
+ ///
+ /// A with helper methods to support .
+ /// This type is primarily needed to avoid having fields being repeated per generic instantiation.
+ ///
+ internal static class ShaderRunner
+ {
+ ///
+ /// A thread-safe map of reusable GPU buffers for captured locals
+ ///
+ [ThreadStatic]
+ private static ConditionalWeakTable>? variablesBuffers;
+
+ ///
+ /// Gets the reusable instance for a shader invocation
+ ///
+ /// The to use to run the shader
+ /// The reusable instance to populate
+ [Pure]
+ public static ConstantBuffer GetVariablesBuffer(GraphicsDevice device)
+ {
+ var map = variablesBuffers ??= new ConditionalWeakTable>();
+
+ return map.GetValue(device, gpu => new ConstantBuffer(gpu, 4096));
+ }
+ }
+
///
/// A responsible for performing all the necessary operations to compile and run a compute shader
///
@@ -98,9 +125,9 @@ namespace ComputeSharp.Shaders
commandList.SetComputeRootDescriptorTable(i + 1, resources[i]);
}
- // Initialize the loop targets
- Span variables = dispatchData.Variables;
- using GraphicsResource variablesBuffer = device.AllocateConstantBuffer(variables);
+ // Initialize the loop targets and the captured values
+ ConstantBuffer variablesBuffer = ShaderRunner.GetVariablesBuffer(device);
+ variablesBuffer.SetData(dispatchData.Variables);
commandList.SetComputeRootDescriptorTable(0, variablesBuffer);
// Calculate the dispatch values