From 753f8a406168f770c9e6a6a37e9199268ed7cd9f Mon Sep 17 00:00:00 2001 From: thiemowmde Date: Tue, 10 Dec 2024 17:35:07 +0100 Subject: [PATCH] Optimize Less_Visitor::visitObj for performance All this small piece of code does are a few string manipulations. It's not very expensive. But called a lot. More than 800,000 times just when running the tests in this codebase. This adds up. Caching the strings in a map reduces the number of calls to how many classes actually exist: only 35. This is well visible in a profile. The relative "self" time spend in this method goes down from 13 to 8. The relative total time for this method goes down as well, from about 190 to 160. Bug: T381895 Change-Id: I10e0c23f72dc5f4babb38f3059716945f5177a4c --- lib/Less/Visitor.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/Less/Visitor.php b/lib/Less/Visitor.php index a7d75ef2..f066aa9e 100644 --- a/lib/Less/Visitor.php +++ b/lib/Less/Visitor.php @@ -13,6 +13,8 @@ public function __construct() { } public function visitObj( $node ) { + static $funcNames = []; + if ( !$node || !is_object( $node ) ) { return $node; } @@ -27,9 +29,10 @@ public function visitObj( $node ) { // // https://packagist.org/packages/brianhenryie/strauss // https://packagist.org/packages/coenjacobs/mozart - $nodeClassNameParts = explode( 'Less_Tree_', get_class( $node ), 2 ); - $nodeType = end( $nodeClassNameParts ); - $funcName = 'visit' . strtr( $nodeType, [ '_' => '', '\\' => '' ] ); + $class = get_class( $node ); + $funcName = $funcNames[$class] ??= 'visit' . str_replace( [ '_', '\\' ], '', + substr( $class, strpos( $class, 'Less_Tree_' ) + 10 ) + ); if ( isset( $this->_visitFnCache[$funcName] ) ) { $visitDeeper = true;