Skip to content

Commit ac26fbb

Browse files
authored
Replace hot Tokenizer loop with a mathematical expression
This piece of code is very hot, executed thousands, possibly millions of times. I found this when I benchmarked our custom sniffs. The replaceTabsInToken() method is consistently reported as one of the absolute hottest ones. I looked at the method and was wondering why this particular piece is a loop when it can be a mathematical expression. According to my micro-benchmark (only measuring the changed piece) it's about twice as fast now. This will probably not have much of an effect in a real-world scenario. Still I find it worth it.
1 parent d2574b9 commit ac26fbb

File tree

1 file changed

+3
-15
lines changed

1 file changed

+3
-15
lines changed

src/Tokenizers/Tokenizer.php

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -642,21 +642,9 @@ public function replaceTabsInToken(&$token, $prefix=' ', $padding=' ', $tabWidth
642642
$tabNum++;
643643

644644
// Move the pointer to the next tab stop.
645-
if (($currColumn % $tabWidth) === 0) {
646-
// This is the first tab, and we are already at a
647-
// tab stop, so this tab counts as a single space.
648-
$currColumn++;
649-
} else {
650-
$currColumn++;
651-
while (($currColumn % $tabWidth) !== 0) {
652-
$currColumn++;
653-
}
654-
655-
$currColumn++;
656-
}
657-
658-
$length += ($currColumn - $lastCurrColumn);
659-
$newContent .= $prefix.str_repeat($padding, ($currColumn - $lastCurrColumn - 1));
645+
$length = $tabWidth - ($currColumn + $tabWidth - 1) % $tabWidth;
646+
$currColumn += $length;
647+
$newContent .= $prefix.str_repeat($padding, ($length - 1));
660648
}//end foreach
661649
}//end if
662650

0 commit comments

Comments
 (0)