Skip to content

Commit

Permalink
Improve performance of function restriction sniffs
Browse files Browse the repository at this point in the history
This abstract sniff is extended by quite a few of our sniffs, and so it has a major impact on the performance of the ruleset as a whole.

Here we make two improvements:

1. We use `isset()` instead of `in_array()`.
2. We don't call `findPrevious()` a second time unless we actually need the information. We only need to check if the namespace is top-level if the function is prefixed with `\\`, the namespace separator.

This seems to improve the performance of these sniffs by as much as 25%.
  • Loading branch information
JDGrimes committed Jan 10, 2017
1 parent 1cc17af commit 4e2d298
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions WordPress/AbstractFunctionRestrictionsSniff.php
Expand Up @@ -150,24 +150,32 @@ public function process( PHP_CodeSniffer_File $phpcsFile, $stackPtr ) {

if ( false !== $prev ) {
// Skip sniffing if calling a same-named method, or on function definitions.
if ( in_array( $tokens[ $prev ]['code'], array( T_FUNCTION, T_DOUBLE_COLON, T_OBJECT_OPERATOR ), true ) ) {
$skipped = array(
T_FUNCTION => T_FUNCTION,
T_DOUBLE_COLON => T_DOUBLE_COLON,
T_OBJECT_OPERATOR => T_OBJECT_OPERATOR,
);

if ( isset( $skipped[ $tokens[ $prev ]['code'] ] ) ) {
return;
}

// Skip namespaced functions, ie: \foo\bar() not \bar().
$pprev = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, ( $prev - 1 ), null, true );
if ( false !== $pprev && T_NS_SEPARATOR === $tokens[ $prev ]['code'] && T_STRING === $tokens[ $pprev ]['code'] ) {
return;
if ( T_NS_SEPARATOR === $tokens[ $prev ]['code'] ) {
$pprev = $phpcsFile->findPrevious( PHP_CodeSniffer_Tokens::$emptyTokens, ( $prev - 1 ), null, true );
if ( false !== $pprev && T_STRING === $tokens[ $pprev ]['code'] ) {
return;
}
}
}
unset( $prev, $pprev );
unset( $prev, $pprev, $skipped );
}

$exclude = explode( ',', $this->exclude );
$exclude = array_flip( explode( ',', $this->exclude ) );

foreach ( $this->groups as $groupName => $group ) {

if ( in_array( $groupName, $exclude, true ) ) {
if ( isset( $exclude[ $groupName ] ) ) {
continue;
}

Expand Down

0 comments on commit 4e2d298

Please sign in to comment.