Skip to content

Commit

Permalink
Optimize Less_Visitor::visitObj for performance
Browse files Browse the repository at this point in the history
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
  • Loading branch information
thiemowmde authored and Daimona committed Dec 10, 2024
1 parent 03ec4c2 commit 753f8a4
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions lib/Less/Visitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ public function __construct() {
}

public function visitObj( $node ) {
static $funcNames = [];

if ( !$node || !is_object( $node ) ) {
return $node;
}
Expand All @@ -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;
Expand Down

0 comments on commit 753f8a4

Please sign in to comment.