diff --git a/.jules/bolt.md b/.jules/bolt.md index d453db43..55c3c58c 100644 --- a/.jules/bolt.md +++ b/.jules/bolt.md @@ -24,3 +24,6 @@ ## 2025-05-21 - Optimized GetRackCount calls (FindObjectsOfType) **Learning:** Using `UnityEngine.Object.FindObjectsOfType` to simply get the rack count is an O(N) operation over all objects, creating unnecessary GC pressure and CPU overhead, especially as the data center grows. **Action:** Optimized `GetRackCount` implementation in `GameHooks.cs` by using the game-managed O(1) singleton `Il2Cpp.NetworkMap.instance.GetNumberOfDevices()` (index 2 for racks), providing a fallback to `FindObjectsOfType` only during uninitialized states. +## 2026-05-25 - Avoid FindObjectsOfType in Scripting Modules +**Learning:** Calling `UnityEngine.Object.FindObjectsOfType` inside Lua modules (like `LuaServerModule`) that are executed during game runtime causes significant CPU and GC spikes, especially when Lua scripts poll state. +**Action:** Always replace these calls with O(1) lookups via game-managed singletons like `Il2Cpp.NetworkMap.instance.servers`, with a fallback to `FindObjectsOfType` only when necessary. diff --git a/src/Infrastructure/Scripting/Lua/Modules/LuaServerModule.cs b/src/Infrastructure/Scripting/Lua/Modules/LuaServerModule.cs index 17bd8abb..cab03065 100644 --- a/src/Infrastructure/Scripting/Lua/Modules/LuaServerModule.cs +++ b/src/Infrastructure/Scripting/Lua/Modules/LuaServerModule.cs @@ -12,6 +12,30 @@ namespace gregCore.Infrastructure.Scripting.Lua.Modules; public static class LuaServerModule { + // Optimization: Use O(1) lookup from game-managed NetworkMap instead of O(N) FindObjectsOfType + private static System.Collections.Generic.IEnumerable GetServers() + { + var nm = Il2Cpp.NetworkMap.instance; + if (nm != null && nm.servers != null) + { + foreach (var kvp in nm.servers) + { + if (kvp.Value != null) yield return kvp.Value; + } + } + else + { + var arr = UnityEngine.Object.FindObjectsOfType(); + if (arr != null) + { + foreach (var s in arr) + { + if (s != null) yield return s; + } + } + } + } + public static void Register(Table greg, Script script, string modId) { var serverTable = new Table(script); @@ -21,7 +45,7 @@ public static void Register(Table greg, Script script, string modId) { try { - var servers = UnityEngine.Object.FindObjectsOfType(); + var servers = GetServers(); var result = new Table(script); int i = 1; foreach (var s in servers) @@ -80,7 +104,7 @@ public static void Register(Table greg, Script script, string modId) { try { - var servers = UnityEngine.Object.FindObjectsOfType(); + var servers = GetServers(); foreach (var s in servers) { try @@ -104,7 +128,7 @@ public static void Register(Table greg, Script script, string modId) try { int repaired = 0; - var servers = UnityEngine.Object.FindObjectsOfType(); + var servers = GetServers(); foreach (var s in servers) { try