MelonLoader

MelonLoader

242 Downloads

[RFC] MelonHandler Events

xKiraiChan opened this issue ยท 5 comments

commented

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() { ... }
commented

I dont see the usage in this, why not just use a bool to handle when its called using ifs?

commented

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:

  1. First a VTable lookup to find the target method
  2. Calling that target method
  3. Comparing the variable
  4. Branching to return

However with events none of that would have to happen

commented
commented

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.

commented

Yea, imma be implementing this