From b16a412b6c293dc346e17d70746f5c2678b0433e Mon Sep 17 00:00:00 2001 From: "google-labs-jules[bot]" <161369871+google-labs-jules[bot]@users.noreply.github.com> Date: Fri, 21 Aug 2026 12:10:35 +0000 Subject: [PATCH] perf: optimize list instantiation in EventBus.Subscribe Co-authored-by: johnstrand <11484777+johnstrand@users.noreply.github.com> --- src/GameUtils/Entity/EventBus.cs | 9 +++- .../EventBusBenchmarks.cs | 42 +++++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 tests/GameUtils.Benchmarks/EventBusBenchmarks.cs diff --git a/src/GameUtils/Entity/EventBus.cs b/src/GameUtils/Entity/EventBus.cs index d5d75f9..a1d57c5 100644 --- a/src/GameUtils/Entity/EventBus.cs +++ b/src/GameUtils/Entity/EventBus.cs @@ -18,11 +18,16 @@ public void Subscribe(Action handler) var type = typeof(TEvent); ref var listObj = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault(_handlers, type, out bool exists); + List> list; if (!exists) { - listObj = new List>(); + list = new List>(); + listObj = list; + } + else + { + list = (List>)listObj!; } - var list = (List>)listObj!; list.Add(handler); _snapshots.Remove(type); } diff --git a/tests/GameUtils.Benchmarks/EventBusBenchmarks.cs b/tests/GameUtils.Benchmarks/EventBusBenchmarks.cs new file mode 100644 index 0000000..50d2918 --- /dev/null +++ b/tests/GameUtils.Benchmarks/EventBusBenchmarks.cs @@ -0,0 +1,42 @@ +using BenchmarkDotNet.Attributes; +using GameUtils.Entity; +using System; + +namespace GameUtils.Benchmarks +{ + [MemoryDiagnoser] + public class EventBusBenchmarks + { + private class TestEvent1 { } + private class TestEvent2 { } + + private Action _handler1 = null!; + private Action _handler2 = null!; + + [GlobalSetup] + public void Setup() + { + _handler1 = e => { }; + _handler2 = e => { }; + } + + [Benchmark] + public void SubscribeNewEvent() + { + var bus = new EventBus(); + bus.Subscribe(_handler1); + bus.Subscribe(_handler2); + } + + [Benchmark] + public void SubscribeExistingEvent() + { + var bus = new EventBus(); + bus.Subscribe(_handler1); + for (int i = 0; i < 100; i++) + { + bus.Subscribe(_handler1); + } + } + } +}