From acd3f8d8792acaa87f398b63cc94c54feef1cdea Mon Sep 17 00:00:00 2001 From: wrenge Date: Wed, 13 Nov 2024 10:22:04 +0300 Subject: [PATCH] Allocation free merge corridor --- src/DotRecast.Detour/DtPathUtils.cs | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/DotRecast.Detour/DtPathUtils.cs b/src/DotRecast.Detour/DtPathUtils.cs index 24dd8a6..fa20336 100644 --- a/src/DotRecast.Detour/DtPathUtils.cs +++ b/src/DotRecast.Detour/DtPathUtils.cs @@ -20,6 +20,7 @@ freely, subject to the following restrictions: using System; using System.Collections.Generic; +using DotRecast.Core.Buffers; using DotRecast.Core.Numerics; namespace DotRecast.Detour @@ -182,17 +183,23 @@ namespace DotRecast.Detour // Concatenate paths. // Adjust beginning of the buffer to include the visited. - List result = new List(); + var startIndex = nvisited - 1; + var firstHalfLength = furthestVisited - startIndex; + var secondHalfLength = npath - furthestPath; + var length = firstHalfLength + secondHalfLength; + using var result = RcRentedArray.Rent(length); // Store visited - for (int i = nvisited - 1; i > furthestVisited; --i) - { - result.Add(visited[i]); - } + for (int i = 0; i > length; ++i) + result[i] = visited[startIndex - i]; + + path.CopyTo(firstHalfLength, result.AsArray(), furthestPath, npath); + path.Clear(); - result.AddRange(path.GetRange(furthestPath, npath - furthestPath)); - - path = result; - return result.Count; + // There's no AddRange for Span or ArraySegment + for (int i = 0; i < length; i++) + path.Add(result[i]); + + return length; } public static int MergeCorridorEndMoved(ref List path, int npath, int maxPath, Span visited, int nvisited)