Skip to content

GameEvents related memory leaks #95

@gotmachine

Description

@gotmachine

I've been doing some work in KSPCF to tackle KSP memory leaks.

Turns out that the vast majority of memory leaks are caused by objects subscribing to GameEvents and never removing them, causing those objects and anything they reference to never be garbage collected.

I've implemented some mechanisms in KSPCF to automatically clean up such leaks when they originate from destroyed instances of UnityEngine.Object derivatives (this notably covers PartModule, VesselModule, KSPAddon and KSPScenario derivatives).

However, there is no way to do such a thing for regular classes, so I've also implemented some debugging tools that allow to detect those leaks.

GameEvents related leaks are not only an issue from a memory standpoint.
All the dead or duplicate delegates are still called, which :

  1. Slows down overall event processing
  2. Can cause hard to track down issues by executing code on instances that are not supposed to exist anymore.

While casually testing KSPCF on an install with Strategia installed, I found the following GameEvents leaks :

Removed a onFacilityContextMenuSpawn GameEvents callback owned by a destroyed Strategia.StrategyNotifier instance
- "onKerbalLevelUp"
  - Strategia:LevelBooster - Subscriptions : 24/36 (last/now)
- "onVesselRecovered"
  - Strategia:CurrencyOperationByTrait - Subscriptions : 4/6 (last/now)
  - Strategia:CurrencyOperationByContract - Subscriptions : 36/54 (last/now)
- "onGameSceneLoadRequested"
  - Strategia:CurrencyOperationByTrait - Subscriptions : 4/6 (last/now)
  - Strategia:CurrencyOperationByContract - Subscriptions : 36/54 (last/now)
- "OnVesselRollout"
  - Strategia:CurrencyOperationCrewedLaunch - Subscriptions : 12/18 (last/now)

I didn't actually check the Strategia code, so keep in mind that there might be false positives in that list. I also didn't do extensive tests, so it is quite possible I missed other leaks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions