New in PHP 8.4: engine optimization of sprintf() to string interpolation

PHPs compiler and bytecode cache OPcache not only cache the compile step from PHP source code to virtual machine bytecode, they also include optimizations that can produce faster bytecode:

For example PHP can:

  • optimize empty functions away. You can see this in a Callgraph Profiler when the function is not appearing in the result. 
  • already compute the result of constant compile time expressions into their result, for example 1 + 1 as 2.
  • replace calls to often used functions with logic directly in the VM to avoid the function call overhead of the engine. We wrote about these compiler optimized functions on this blog before.

For PHP 8.4 Tideways sponsored the work of our colleague Tim to add another compiler optimization for the function sprintf().

If you call the function with a format string containing only %s placeholders the engine will compile the call to sprintf() directly into the equivalent string interpolation, removing the overhead of the function call and avoiding repeatedly parsing the format string.

Taking an example from our code-base, we build many of our Redis cache keys using sprintf() and a pattern like this:

private function key(string $type, int $identifier): string
{
 return sprintf('last_ts_%s_%s', $type, $identifier);
}

With this optimization, the engine will automatically rewrite it to look like this code:

private function key(string $type, int $identifier): string
{
  return "last_ts_{$type}_{$identifier}";
}

This optimization will happen automatically during compilation of any PHP script and requires no work on your end.

We quickly followed up on this initial optimization with another pull request to add support for the %d placeholder.

Support for just these two placeholders allows the optimization to apply to more than 90% of the format strings encountered in the landing page of PHP’s Symfony Benchmark.

Given the widespread use of sprintf() in common PHP code (616 times in Tideways own backend code) this is an optimization that will make a small but significant contribution for the overall PHP performance.

With this optimization in mind, it also enables you to write or rewrite string manipulation code that is already performance sensitive to use sprintf() for better readability without making it slower.

What an AI would never be able to tell you the way we can! Follow us on LinkedIn or X and subscribe to our newsletter to take a deep dive into technical issues surrounding PHP performance.

You’ll never know until you try … our free trial!

Benjamin Benjamin 18.06.2024