Compiler Optimized Functions

There are some PHP functions that the PHP compiler can optimize to a more efficient opcode-based representation. In this optimization a significant part of the function call overhead of these internal PHP functions can be circumvented.

To trigger this optimization, you must be careful to call internal functions directly from the global namespace and not rely on the automatic fallback.


namespace MyApp;

use function count;

// Cannot be optimized since it might be MyApp\strlen
echo strlen("foo");

// can be optimized, directly called in global namespace
echo \strlen("bar");

// can be optimized, imported via "use function".
echo count(["foo"]);

Normally, this optimization does not make a big performance difference in regular code and should be considered a micro-optimization.

Only if you call these functions many hundred-thousands of times will you see an actual difference. But these functions are optimized precisely because it is not unreasonable that they get called this often in a script.

The Tideways Callgraph Profiler will help you find the cases where this optimization makes sense for you.

php-cs-fixer can automate work with compiler optimized functions

For php-cs-fixer there is the native_function_invocation rule with the default configuration setting @compiler_optimized:

php php-cs-fixer-v3.phar fix src/ --allow-risky=yes --rules=native_function_invocation

List of compiler optimized functions

You can find the list in zend_compile.c in the PHP source code, as of PHP 8.1 these are:

  • strlen

  • is_null

  • is_bool

  • is_long

  • is_int and is_integer

  • is_float and is_double

  • is_string

  • is_array

  • is_object

  • is_resource

  • is_scalar

  • boolval

  • intval

  • floatval and doubleval

  • strval

  • defined

  • chr

  • ord

  • call_user_func_array

  • call_user_func

  • in_array

  • count and sizeof

  • get_class

  • get_called_class

  • gettype

  • func_num_args

  • func_get_args

  • array_slice

  • array_key_exists

Still need help? Email [email protected]