[RFC] MelonHandler Events
xKiraiChan opened this issue ยท 5 comments
Events are a common pattern in F# and JavaScript.
I am pretty sure that none of the MelonMod
overrides return a value so this system should work perfectly.
Delegate invocation (events) has the same speed as virtual invocation (interfaces), so there shouldn't be a performance hit, rather there would've been a performance increase, unfortunately this will not be gained due to backwards compatibility.
Additionally, multiple functions can subscribe to an event, which can result in cleaner looking code instead of a monolithic override function.
Another benefit is unsubscribing from events, instead of if (!enabled) return;
being ran every single time the function is called, the function won't get called at all (faster).
Example:
public Mod() { // class constructor
MelonHandler.OnUpdate += Update;
}
// this could be useful for a 0Reloader plugin if that ever happens
~Mod() { // finalizer/destructor
MelonHandler.OnUpdate -= Update;
}
void Update() { ... }
I dont see the usage in this, why not just use a bool to handle when its called using ifs?
I dont see the usage in this, why not just use a bool to handle when its called using ifs?
Performance and readability
This gets ran every time the method gets called, even if a mod is not overriding the virtual method:
- First a VTable lookup to find the target method
- Calling that target method
- Comparing the variable
- Branching to return
However with events none of that would have to happen
I already had this idea before. A goal I wanna achieve in the new ML rewrite is to use more events and make less external references. This will not only improve the structure, but will also allow plugin devs for a lot of freedom in general.
For mod devs, this would help them keeping a cleaner structure.
I also agree with xKiraiChan's points.