From 4a4d140350dbf6bea14a5ce2f5a3d3c6c69522c6 Mon Sep 17 00:00:00 2001 From: jrfnl Date: Fri, 2 Jun 2023 11:21:14 +0200 Subject: [PATCH] PSR12/OpenTag: improve performance No functional changes at all, just improving performance of the sniff by changing the order of certain checks. Some benchmarks for this change run using the Performance report (PR 3810): Command: `phpcs -ps . --extensions=php --ignore=/vendor/ --report=performance --standard=psr12` Output for the `PSR12.Files.OpenTag` sniff: Result | PHPCS itself | Set of Projects A | Set of Projects B | Set of Projects C | ------ | ------------------ | ------------------ | ------------------ | ----------------- | Nr of Files Scanned | 614 | 4115 | 25546 | 2250 | Before | 0.077045 ( 2.3 %) | 0.982014 ( 1.9 %) | 3.267655 ( 2.1 %) | 0.179564 ( 2.1 %) After | 0.000928 ( 0.0 %) | 0.013066 ( 0.0 %) | 0.091816 ( 0.1 %) | 0.109021 ( 1.3 %) With what the sniff does, the impact is biggest for files/codebases which already comply with the expectations of this sniff. --- .../PSR12/Sniffs/Files/OpenTagSniff.php | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/Standards/PSR12/Sniffs/Files/OpenTagSniff.php b/src/Standards/PSR12/Sniffs/Files/OpenTagSniff.php index 4371bee19b..befb49ecbc 100644 --- a/src/Standards/PSR12/Sniffs/Files/OpenTagSniff.php +++ b/src/Standards/PSR12/Sniffs/Files/OpenTagSniff.php @@ -44,25 +44,28 @@ public function process(File $phpcsFile, $stackPtr) return $phpcsFile->numTokens; } - $next = $phpcsFile->findNext(T_INLINE_HTML, 0); - if ($next !== false) { - // This rule only applies to PHP-only files. - return $phpcsFile->numTokens; - } - $tokens = $phpcsFile->getTokens(); $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true); if ($next === false) { // Empty file. - return; + return $phpcsFile->numTokens; + } + + if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) { + // Tag is on a line by itself. + return $phpcsFile->numTokens; + } + + $next = $phpcsFile->findNext(T_INLINE_HTML, 0); + if ($next !== false) { + // This rule only applies to PHP-only files. + return $phpcsFile->numTokens; } - if ($tokens[$next]['line'] === $tokens[$stackPtr]['line']) { - $error = 'Opening PHP tag must be on a line by itself'; - $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotAlone'); - if ($fix === true) { - $phpcsFile->fixer->addNewline($stackPtr); - } + $error = 'Opening PHP tag must be on a line by itself'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotAlone'); + if ($fix === true) { + $phpcsFile->fixer->addNewline($stackPtr); } return $phpcsFile->numTokens;