Skip to content

30: Faster printf() with Simple Formats

Print a short inventory report using the format specifiers the compiler can optimize. The source remains ordinary printf().

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable printf-performance.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/30-printf-performance/printf-performance.php
printf-performance.php
<?php
declare(strict_types=1);
$warehouse = 'South';
$count = 7;
printf("%s has %d orders\n", $warehouse, $count);
printf("Batch %04d\n", $count);
South has 7 orders
Batch 0007

PHP 8.6 can compile eligible calls with literal format strings using %s and %d into equivalent string operations. Formatting features such as zero padding still have their normal output. Keep the format that expresses the output you need.

Change the format for the second line to %d and check that the leading zeroes disappear.

Continue with Caching Stateless Closures.