diff --git a/SpectralConvolution/SpectralConvolution/KernelSpectrum.cs b/SpectralConvolution/SpectralConvolution/KernelSpectrum.cs index 26f4d96..fdc5db2 100644 --- a/SpectralConvolution/SpectralConvolution/KernelSpectrum.cs +++ b/SpectralConvolution/SpectralConvolution/KernelSpectrum.cs @@ -4,8 +4,8 @@ namespace SpectralConvolution; internal sealed class KernelSpectrum { - readonly ComplexLines rows = new(); - readonly ComplexLines column = new(); + static readonly ScratchPool Scratches = new(Environment.ProcessorCount); + double[] kernel = []; Float2[] twiddles = []; Float2[] spectrum = []; @@ -45,6 +45,9 @@ internal sealed class KernelSpectrum Radius = 0; if (kernel.Length < kernelArea) kernel = new double[kernelArea]; + using var lease = Scratches.Rent(); + var rows = lease.Value.Rows; + var column = lease.Value.Column; rows.Ensure(rowArea); column.Ensure(size); if (spectrum.Length < size * size) @@ -112,4 +115,10 @@ internal sealed class KernelSpectrum } public static float Flush(float value) => float.IsSubnormal(value) ? float.CopySign(0f, value) : value; + + sealed class TransformScratch + { + public readonly ComplexLines Rows = new(); + public readonly ComplexLines Column = new(); + } } diff --git a/SpectralConvolution/SpectralConvolution/ScratchPool.cs b/SpectralConvolution/SpectralConvolution/ScratchPool.cs new file mode 100644 index 0000000..d57b68d --- /dev/null +++ b/SpectralConvolution/SpectralConvolution/ScratchPool.cs @@ -0,0 +1,48 @@ +namespace SpectralConvolution; + +internal sealed class ScratchPool(int capacity) where T : class, new() +{ + readonly T?[] slots = new T?[capacity]; + readonly object gate = new(); + + public Lease Rent() + { + T? item = null; + lock (gate) + { + for (var index = 0; index < slots.Length; index++) + { + if (slots[index] is not { } found) + continue; + + item = found; + slots[index] = null; + break; + } + } + + return new Lease(this, item ?? new T()); + } + + void Return(T item) + { + lock (gate) + { + for (var index = 0; index < slots.Length; index++) + { + if (slots[index] is not null) + continue; + + slots[index] = item; + return; + } + } + } + + public readonly struct Lease(ScratchPool pool, T value) : IDisposable + { + public T Value { get; } = value; + + public void Dispose() => pool.Return(Value); + } +}