From a3422c7c2991eb1a5b9d05c1187817120afcaa57 Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Tue, 17 Mar 2026 08:26:33 +0100 Subject: [PATCH] Use pooled arrays during list completion. --- .../Processing/ValueCompletion.List.cs | 55 +++++++++++++------ 1 file changed, 38 insertions(+), 17 deletions(-) diff --git a/src/HotChocolate/Core/src/Types/Execution/Processing/ValueCompletion.List.cs b/src/HotChocolate/Core/src/Types/Execution/Processing/ValueCompletion.List.cs index 66633045b89..8c51ea3e28c 100644 --- a/src/HotChocolate/Core/src/Types/Execution/Processing/ValueCompletion.List.cs +++ b/src/HotChocolate/Core/src/Types/Execution/Processing/ValueCompletion.List.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Collections; using System.Text.Json; using HotChocolate.Text.Json; @@ -96,31 +97,51 @@ private static void CompleteListValue( if (runtimeValue is IEnumerable enumerable) { - var i = 0; - var temp = new List(); + var count = 0; + var buffer = ArrayPool.Shared.Rent(64); - foreach (var value in enumerable) + try { - temp.Add(value); - } + foreach (var value in enumerable) + { + if (count == buffer.Length) + { + var newBuffer = ArrayPool.Shared.Rent(buffer.Length * 2); + var span = buffer.AsSpan(0, count); + span.CopyTo(newBuffer); + span.Clear(); + ArrayPool.Shared.Return(buffer); + buffer = newBuffer; + } + + buffer[count++] = value; + } - resultValue.SetArrayValue(temp.Count); + resultValue.SetArrayValue(count); - foreach (var element in resultValue.EnumerateArray()) - { - Complete( - context, - selection, - elementType, - element, - temp[i++]); + var i = 0; - // if we ran into an error that invalidated the result we abort. - if (element.IsInvalidated) + foreach (var element in resultValue.EnumerateArray()) { - return; + Complete( + context, + selection, + elementType, + element, + buffer[i++]); + + // if we ran into an error that invalidated the result we abort. + if (element.IsInvalidated) + { + return; + } } } + finally + { + buffer.AsSpan(0, count).Clear(); + ArrayPool.Shared.Return(buffer); + } return; }