1.2.1108. Should Use Function

Functioncalls that fall back to global scope should be using ‘use function’ or be fully namespaced.

PHP searches for functions in the local namespaces, and in case it fails, makes the same search in the global scope. Anytime a native function is referenced this way, the search (and fail) happens. This slows down the scripts.

The speed bump range from 2 to 8 %, depending on the availability of functions in the local scope. The overall bump is about 1 µs per functioncall, which makes it a micro optimisation until a lot of function calls are made.

Based on one of Marco Pivetta tweet. This analysis is a related to Performances/Php74ArrayKeyExists, and is a more general version.

<?php

namespace X {
    use function strtolower as strtolower_aliased;

    // PHP searches for strtolower in X, fails, then falls back to global scope, succeeds.
    $a = strtolower($b);

    // PHP searches for strtolower in global scope, succeeds.
    $a = \strtolower($b);

    // PHP searches for strtolower_aliased in global scope, succeeds.
    $a = \strtolower_aliased($b);
}

?>

See also blog post.

1.2.1108.1. Suggestions

  • Use the use command for arrray_key_exists(), at the beginning of the script

  • Use an initial before array_key_exists()

  • Remove the namespace

1.2.1108.2. Specs

Short name

Php/ShouldUseFunction

Rulesets

All, Performances

Exakat since

0.9.5

PHP Version

All

Severity

Minor

Time To Fix

Slow (1 hour)

Precision

Very high

Available in

Entreprise Edition, Exakat Cloud