From d04da9b1d8292e8f5b8ca699ba68917d3b3a8f7c Mon Sep 17 00:00:00 2001 From: "Dylan K. Taylor" Date: Sat, 6 May 2023 15:42:52 +0100 Subject: [PATCH] Reuse timings handlers for event handlers of the same events due to direct repeated usage of registerEvent() with closures, we've seen some libraries like muqsit/SimplePacketHandler generate very large timings reports, because a new timings handler gets created every time a plugin registers or unregisters a new packet handler callback. This change fixes the problem by ensuring that any handlers derived from the same function, handling the same event class, will share the same timer. --- src/plugin/PluginManager.php | 4 ++-- src/timings/Timings.php | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/plugin/PluginManager.php b/src/plugin/PluginManager.php index d109b23face..725c915a1e9 100644 --- a/src/plugin/PluginManager.php +++ b/src/plugin/PluginManager.php @@ -37,7 +37,7 @@ use pocketmine\permission\PermissionManager; use pocketmine\permission\PermissionParser; use pocketmine\Server; -use pocketmine\timings\TimingsHandler; +use pocketmine\timings\Timings; use pocketmine\utils\AssumptionFailedError; use pocketmine\utils\Utils; use Symfony\Component\Filesystem\Path; @@ -651,7 +651,7 @@ public function registerEvent(string $event, \Closure $handler, int $priority, P throw new PluginException("Plugin attempted to register event handler " . $handlerName . "() to event " . $event . " while not enabled"); } - $timings = new TimingsHandler($handlerName . "(" . (new \ReflectionClass($event))->getShortName() . ")", group: $plugin->getDescription()->getFullName()); + $timings = Timings::getEventHandlerTimings($event, $handlerName, $plugin->getDescription()->getFullName()); $registeredListener = new RegisteredListener($handler, $priority, $plugin, $handleCancelled, $timings); HandlerListManager::global()->getListFor($event)->register($registeredListener); diff --git a/src/timings/Timings.php b/src/timings/Timings.php index a400a73b4f7..74fa40dde5e 100644 --- a/src/timings/Timings.php +++ b/src/timings/Timings.php @@ -166,6 +166,8 @@ abstract class Timings{ /** @var TimingsHandler[] */ private static array $events = []; + /** @var TimingsHandler[][] */ + private static array $eventHandlers = []; public static function init() : void{ if(self::$initialized){ @@ -336,4 +338,16 @@ public static function getEventTimings(Event $event) : TimingsHandler{ return self::$events[$eventClass]; } + + /** + * @phpstan-template TEvent of Event + * @phpstan-param class-string $event + */ + public static function getEventHandlerTimings(string $event, string $handlerName, string $group) : TimingsHandler{ + if(!isset(self::$eventHandlers[$event][$handlerName])){ + self::$eventHandlers[$event][$handlerName] = new TimingsHandler($handlerName . "(" . self::shortenCoreClassName($event, "pocketmine\\event\\") . ")", group: $group); + } + + return self::$eventHandlers[$event][$handlerName]; + } }