30: Faster printf() with Simple Formats
Overview
Section titled “Overview”Print a short inventory report using the format specifiers the compiler can optimize. The source remains ordinary printf().
Prerequisites
Section titled “Prerequisites”- 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.
What You’ll Build
Section titled “What You’ll Build”A runnable printf-performance.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/30-printf-performance/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);Expected Result
Section titled “Expected Result”South has 7 ordersBatch 0007Why It Works
Section titled “Why It Works”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.
Exercise
Section titled “Exercise”Change the format for the second line to %d and check that the leading zeroes disappear.
Wrap-up
Section titled “Wrap-up”Continue with Caching Stateless Closures.