Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/GameUtils/Entity/EventBus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,16 @@ public void Subscribe<TEvent>(Action<TEvent> handler)
var type = typeof(TEvent);

ref var listObj = ref System.Runtime.InteropServices.CollectionsMarshal.GetValueRefOrAddDefault(_handlers, type, out bool exists);
List<Action<TEvent>> list;
if (!exists)
{
listObj = new List<Action<TEvent>>();
list = new List<Action<TEvent>>();
listObj = list;
}
else
{
list = (List<Action<TEvent>>)listObj!;
}
var list = (List<Action<TEvent>>)listObj!;
list.Add(handler);
_snapshots.Remove(type);
}
Expand Down
42 changes: 42 additions & 0 deletions tests/GameUtils.Benchmarks/EventBusBenchmarks.cs
Original file line number Diff line number Diff line change
@@ -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<TestEvent1> _handler1 = null!;
private Action<TestEvent2> _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);
}
}
}
}
Loading