mardi 5 mai 2020

Faster calling of methods using reflection

I'm porting over some old code from AS3 (via Haxe) to C#.
Parts of the code are transpiled, others I have manually rewritten in C#. One of these parts is the event dispatching.

I have event listeners registering to an event dispatcher, all listeners have a signature like this:

public void handleSomething(Event e)
// they may also use a subclass of Event as a parameter
public void handleAnother(MouseEvent e)

The events keep a small amount of data and a type:

public class Event {

    public const string ENTER_FRAME = "enter_frame";
    public const string RESIZE = "resize";
    public const string CHANGE = "change";

    readonly string type;

    public Event(string type) {
        this.type = type;
    }
}

I keep a list keyed on the particular event type (a string, due to legacy reasons), once an event is dispatched I find the appropriate handlers keyed with that string and call the them with the event data.

I am currently using reflection to do this, but it is proving to be prohibitively slow. I have found several threads that share this problem.

My particular issue is that the method signature varies, if it was always an Event as a parameter I could use the solutions provided, but alas.

I'd be fine with trading some memory/time at setup to get subsequent calls to be faster. I can get a reference to the method and work out what type it expects, but I'm unsure how to store and call this later?





Aucun commentaire:

Enregistrer un commentaire