I have extended this class http://wiki.unity3d.com/index.php/CSharpMessenger_Extended to accept strings containing wildcards as eventTypes
, therefore I am able to write things like
Messenger.AddListener("*", () => Console.WriteLine("woohoo, generic handler"));
But I am highly concerned about the performance of this implementation.
I've extended the Dictionary class like this:
public class EventDictionary : Dictionary<string, Delegate>
{
public Delegate[] GetHandlers(string Event)
{
List<Delegate> matches = new List<Delegate>();
foreach (string pattern in Keys)
if (Regex.IsMatch(Event, Regex.Escape(pattern).Replace( @"\*", ".*" ).Replace( @"\?", "." )))
matches.Add(this[pattern]);
UnityEngine.Debug.Log(matches.Count);
return matches.ToArray();
}
}
As you see, for every key in the dictionary, I first convert it to a regular expression, then check if it is a match for the event name, if it's so, add it to a collection and return the array.
But, this code runs in a game where the messenger script is used frequently, therefore I am really concerned about the performance of this approach.
I think storing regex's directly in the dictionary would be better but my main concern is about the regex matching.
Is my solution acceptable? If not what would be a better approach for solving my problem?