From 89e96992c2a82a50e178adbaeca60ebd11cddb4d Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Sat, 12 Sep 2026 19:36:49 +0000 Subject: [PATCH] Optimize VirtualMemory.TryValidateRange hot path - Converts the `while(true)` loop to a `for` loop to allow the JIT compiler to elide bounds checks. - Eliminates `Math.Min` and redundant branch checks. - Removes unnecessary `ulong` to `int` casting. Co-authored-by: manupawickramasinghe <73810867+manupawickramasinghe@users.noreply.github.com> --- src/SharpEmu.Core/Memory/VirtualMemory.cs | 29 ++++++++--------------- 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/src/SharpEmu.Core/Memory/VirtualMemory.cs b/src/SharpEmu.Core/Memory/VirtualMemory.cs index 7496dc42f..d6d4ee251 100644 --- a/src/SharpEmu.Core/Memory/VirtualMemory.cs +++ b/src/SharpEmu.Core/Memory/VirtualMemory.cs @@ -127,6 +127,7 @@ public bool TryWrite(ulong virtualAddress, ReadOnlySpan source) return true; } + /// Performance optimization: Elides Math.Min calls, redundant branch checks, and casting inside the hot path validation loop for optimal MSIL generation. private bool TryValidateRange( ulong virtualAddress, int length, @@ -141,16 +142,11 @@ private bool TryValidateRange( var span = System.Runtime.InteropServices.CollectionsMarshal.AsSpan(_regions); var currentAddress = virtualAddress; - var remaining = length; - var currentIndex = regionIndex; - while (true) - { - if (currentIndex >= span.Length) - { - return false; - } + var remaining = (ulong)length; - ref var region = ref span[currentIndex]; + for (var i = regionIndex; i < span.Length; i++) + { + ref var region = ref span[i]; if (currentAddress < region.Region.VirtualAddress || currentAddress >= region.EndAddress || (region.Region.Protection & requiredProtection) == 0) @@ -158,22 +154,17 @@ private bool TryValidateRange( return false; } - if (remaining == 0) - { - return true; - } - var available = region.EndAddress - currentAddress; - var chunkLength = (int)Math.Min((ulong)remaining, available); - remaining -= chunkLength; - if (remaining == 0) + if (remaining <= available) { return true; } - currentAddress += (ulong)chunkLength; - currentIndex++; + remaining -= available; + currentAddress += available; } + + return false; } private int FindContainingRegionIndex(ulong virtualAddress)