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); + } + } + } +}