From 270c37764edc9b48f4208df1b9bffffbc1947c5e Mon Sep 17 00:00:00 2001 From: Gustas <37534529+PunkPun@users.noreply.github.com> Date: Sat, 9 Aug 2025 21:15:40 +0300 Subject: [PATCH] Reduce MersenneTwister memory allocation --- OpenRA.Game/Support/MersenneTwister.cs | 17 ++++++++--------- OpenRA.Mods.Common/MapGenerator/MultiBrush.cs | 2 +- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/OpenRA.Game/Support/MersenneTwister.cs b/OpenRA.Game/Support/MersenneTwister.cs index 2ad40fb033..4adedba199 100644 --- a/OpenRA.Game/Support/MersenneTwister.cs +++ b/OpenRA.Game/Support/MersenneTwister.cs @@ -10,7 +10,6 @@ #endregion using System; -using System.Collections.Generic; namespace OpenRA.Support { @@ -99,23 +98,23 @@ namespace OpenRA.Support /// /// Pick a random index from a list of weights. /// - public int PickWeighted(IReadOnlyList weights) + public int PickWeighted(ReadOnlySpan weights) { ulong total = 0; - foreach (var weight in weights) + for (var i = 0; i < weights.Length; i++) { + var weight = weights[i]; if (weight < 0) throw new ArgumentException("Found a negative weight."); total += (ulong)weight; } if (total == 0) - return Next(0, weights.Count); + return Next(0, weights.Length); var spin = NextUlong() % total; - int i; ulong acc = 0; - for (i = 0; i < weights.Count; i++) + for (var i = 0; i < weights.Length; i++) { acc += (ulong)weights[i]; if (spin < acc) @@ -128,13 +127,13 @@ namespace OpenRA.Support /// /// Shuffle a portion of a list in place. Has minor biases. /// - public void ShuffleInPlace(IList list, int start, int len) + public void ShuffleInPlace(Span span, int start, int len) { for (var i = len; i > 1; i--) { var swap = Next(i); - (list[start + i - 1], list[start + swap]) = - (list[start + swap], list[start + i - 1]); + (span[start + i - 1], span[start + swap]) = + (span[start + swap], span[start + i - 1]); } } diff --git a/OpenRA.Mods.Common/MapGenerator/MultiBrush.cs b/OpenRA.Mods.Common/MapGenerator/MultiBrush.cs index cb518eb21d..8aaf72e7e0 100644 --- a/OpenRA.Mods.Common/MapGenerator/MultiBrush.cs +++ b/OpenRA.Mods.Common/MapGenerator/MultiBrush.cs @@ -678,7 +678,7 @@ namespace OpenRA.Mods.Common.MapGenerator mposCount++; } - random.ShuffleInPlace(mposes, 0, mposCount); + random.ShuffleInPlace(mposes.AsSpan(), 0, mposCount); } Replaceability ReserveShape(CPos paintAt, IEnumerable shape, Replaceability contract)