Someone replaced a foreach with a collect()->map()->filter()->sum() inside an invoice totaliser. Tests passed. Pint passed. PHPStan passed. Four months later the nightly billing run took forty minutes instead of nine, and nobody could say which commit did it.
There was no gate on speed, because there rarely is. This is the one I use: PHPBench measuring the units I actually control, a baseline stored from the target branch, and an assertion that fails the GitHub Actions build when a pull request makes something meaningfully slower.
Pick a unit worth benchmarking#
Benchmark something with a stable input and no network, no clock and no randomness. In a typical Laravel app that means a pricing or totalling service, a serialiser or DTO mapper, a parser, a permission resolver, a collection pipeline over a fixed fixture, or a query builder path you can exercise without hitting the database.
Do not benchmark a controller or a full request. On a shared runner that measurement is dominated by boot time, filesystem speed and whatever else is on the box, and you will get a 15% swing between two runs of identical code. The useful rule: if you cannot explain every microsecond in the measurement, it is not a regression test, it is a mood ring.
For the rest of this article the subject is an InvoiceTotaliser that takes a fixed set of line items and returns a total with tax and discounts applied.
Install PHPBench and configure it#
PHPBench installs as a dev dependency. The current stable line is 1.7, which dropped PHP 8.2 in 1.5.0 and added PHP 8.5 support in the same release, so a modern Laravel project is well inside the supported range.
composer require --dev phpbench/phpbench "^1.7"
Then a phpbench.json in the project root. runner.bootstrap points at Composer's autoloader so your classes resolve, and runner.path tells the runner where the benchmark files live:
{
"$schema": "./vendor/phpbench/phpbench/phpbench.schema.json",
"runner.bootstrap": "vendor/autoload.php",
"runner.path": "tests/Benchmark",
"runner.file_pattern": "*Bench.php",
"runner.retry_threshold": 5
}
Two settings worth knowing about. runner.subject_pattern defaults to ^bench, so every benchmark method must be named benchSomething(). And storage.xml_storage_path defaults to .phpbench/storage — that directory is where tagged runs live, so add .phpbench to .gitignore now rather than committing a few hundred kilobytes of XML later.
Write the first benchmark#
A benchmark class is a plain PHP class with bench-prefixed methods. Metadata comes from PHP 8 attributes under the PhpBench\Attributes namespace — the older docblock annotations still work, but there is no reason to write new ones.
<?php
declare(strict_types=1);
namespace Tests\Benchmark;
use App\Billing\InvoiceTotaliser;
use App\Billing\LineItem;
use PhpBench\Attributes as Bench;
#[Bench\BeforeMethods('setUp')]
#[Bench\OutputTimeUnit('microseconds')]
final class InvoiceTotaliserBench
{
private InvoiceTotaliser $totaliser;
/** @var list<LineItem> */
private array $items;
public function setUp(): void
{
$this->totaliser = new InvoiceTotaliser();
// Fixture built once per subject, outside the measured window.
$this->items = array_map(
static fn (int $i): LineItem => new LineItem("SKU-{$i}", quantity: 3, unitPrice: 1299),
range(1, 200),
);
}
#[Bench\Revs(500)]
#[Bench\Iterations(10)]
#[Bench\Warmup(1)]
public function benchTotal(): void
{
$this->totaliser->total($this->items);
}
}
#[Bench\Revs(500)] means the method body runs 500 times inside a single timed window, and the reported figure is that window divided by 500 — which is how you get useful numbers out of a method that takes a few microseconds. #[Bench\Iterations(10)] means that whole window is repeated ten times, giving PHPBench ten samples to compute a distribution from. #[Bench\Warmup(1)] runs one unmeasured window first so OPcache and lazy initialisation are not charged to your first sample.
Rule of thumb: pick revs so a single measured window lands in the millisecond range, then use eight to ten iterations. If the subject already takes milliseconds on its own, drop revs to 1 and raise iterations instead.
Run it:
vendor/bin/phpbench run --report=aggregate
Read the report before you trust it#
The aggregate report gives you the numbers that matter, and one of them is a trust score.
+-----------------------+-----------+-----+------+-----+-----------+-----------+--------+
| benchmark | subject | set | revs | its | mem_peak | mode | rstdev |
+-----------------------+-----------+-----+------+-----+-----------+-----------+--------+
| InvoiceTotaliserBench | benchTotal| 0 | 500 | 10 | 1.902mb | 184.221μs | ±1.42% |
+-----------------------+-----------+-----+------+-----+-----------+-----------+--------+
mode is the KDE mode of the per-iteration averages — the value the distribution clusters around, which is more robust than a mean when one iteration gets interrupted. rstdev is the relative standard deviation across iterations, and it is the number to look at first. Under about 2% the benchmark is stable enough to assert on. Above 5% you are measuring the machine: raise revs, raise iterations, or accept that this subject is not a regression candidate.
PHPBench also has a --retry-threshold that re-runs iterations deviating beyond a given percentage, which is the cheapest way to pull rstdev down before you reach for anything else.
Boot Laravel only when the code needs it#
Plenty of worthwhile subjects need the container — anything resolving config, a cache repository or a bound interface. Bootstrap the framework in a before-method so the boot cost sits outside the measured window:
<?php
declare(strict_types=1);
namespace Tests\Benchmark;
use App\Pricing\PriceResolver;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Application;
use PhpBench\Attributes as Bench;
#[Bench\BeforeMethods('bootLaravel')]
final class PriceResolverBench
{
private Application $app;
private PriceResolver $resolver;
public function bootLaravel(): void
{
$this->app = require __DIR__.'/../../bootstrap/app.php';
$this->app->make(Kernel::class)->bootstrap();
// Resolve once: container resolution is not what we are measuring.
$this->resolver = $this->app->make(PriceResolver::class);
}
#[Bench\Revs(200)]
#[Bench\Iterations(10)]
public function benchResolve(): void
{
$this->resolver->forSku('SKU-1', quantity: 3);
}
}
Two things to be deliberate about. Resolve the subject out of the container in the before-method, not inside benchTotal(), or you are benchmarking the container. And keep the database out of it — if the code under test reads rows, either stub the repository or accept that you are now benchmarking SQLite's page cache. A benchmark that touches real I/O belongs in a load test, not a CI gate.
Store a baseline and assert against it#
A benchmark only becomes a regression test when there is something to compare against. PHPBench stores tagged runs and can reference them later.
Run on the code you want to compare to, and tag it:
vendor/bin/phpbench run --tag=base --retry-threshold=5 --iterations=10
Switch to the new code and reference that tag:
vendor/bin/phpbench run --report=aggregate --ref=base --retry-threshold=5 --iterations=10
With a reference present, the mean, mode and rstdev columns show the percentage difference against the stored run. To make it fail rather than merely inform, add an assertion:
vendor/bin/phpbench run \
--ref=base \
--retry-threshold=5 \
--iterations=10 \
--assert="mode(variant.time.avg) < mode(baseline.time.avg) +/- 10%"
That reads as: the mode of this run must be below the baseline's mode, tolerating a 10% band either side. A failed assertion exits non-zero, which is the whole point.
Use a percentage band, not an absolute ceiling. mode(variant.time.avg) < 200 microseconds is valid syntax and a trap — it encodes your laptop's speed into the repository, and the first time GitHub gives you a slower runner class, every PR goes red. You can also set a project-wide default with "runner.assert" in phpbench.json and override per subject with #[Bench\Assert(...)].
Wire the gate into GitHub Actions#
The reliable shape is one job that benchmarks the base commit, then benchmarks the head commit against it, on the same runner in the same process environment. Comparing across two different runners is where flaky benchmark gates come from.
name: Benchmarks
on:
pull_request:
jobs:
phpbench:
name: Performance regression
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.4'
# Xdebug makes every measurement meaningless.
coverage: none
extensions: mbstring, intl
ini-values: opcache.enable_cli=1, zend.assertions=-1
- name: Install dependencies
run: composer install --no-interaction --no-progress --prefer-dist
- name: Benchmark the base branch
run: |
git checkout --quiet ${{ github.event.pull_request.base.sha }} -- src tests
vendor/bin/phpbench run --progress=plain --tag=base --retry-threshold=5 --iterations=10
git checkout --quiet ${{ github.sha }} -- src tests
- name: Compare this PR against the base
run: |
vendor/bin/phpbench run \
--progress=plain \
--report=aggregate \
--ref=base \
--retry-threshold=5 \
--iterations=10 \
--assert="mode(variant.time.avg) < mode(baseline.time.avg) +/- 10%"
Checking out only the source paths keeps vendor/ and the .phpbench/storage directory intact between the two runs, so the tag written by the first step is still there for the second. If your benchmarks resolve autoloaded classes added by the PR, run composer dump-autoload between the checkouts.
Pin the PHP version explicitly — a benchmark gate on php-version: '8.4' compared against a baseline built on a different minor is comparing two languages. The same discipline that makes matrix testing across PHP and database versions trustworthy applies doubly here. And because this job installs dependencies twice a day across every PR, it is worth caching Composer and npm in the workflow so the gate costs seconds rather than minutes.
Here is what a caught regression looks like — the collect() pipeline landing in the totaliser:
InvoiceTotaliserBench
benchTotal.....................I9 - [Mo417.882μs vs. Mo184.221μs] +126.8% (±1.91%)
1 subjects, 10 iterations, 5,000 revs
[FAILED] mode(variant.time.avg) < mode(baseline.time.avg) +/- 10%
417.882μs is not less than 184.221μs +/- 18.422μs
Tame the noise on shared runners#
Shared CI runners are unstable environments, and the PHPBench documentation says so plainly. You can reliably catch major regressions; you cannot reliably catch 3%.
What actually helps, in order of effect: turn Xdebug off — it is the single biggest distortion, which is also why PCOV is the right choice for coverage in Laravel CI. Set a retry threshold of 5 so unstable iterations are re-sampled. Use ten iterations rather than three. Keep the tolerance band at 10% or wider until you have seen a week of real numbers. And keep the benchmark job alone in its own workflow job so a parallel test suite is not competing for the same CPU.
A few failure modes that will bite you regardless:
A benchmark added by the pull request has no counterpart in the baseline run, so there is nothing to compare and the assertion silently passes for that subject. Expect the first run of any new benchmark to be ungated.
Memory figures move for reasons unrelated to your change — mem_peak includes the PHP process, so assert on time, not memory, unless the subject is specifically about allocation.
OPcache state differs between the runner and your laptop. PHPBench records environment information including OPcache status with each run, so when a number looks impossible, check that first. If your production tuning depends on it, the behaviour under OPcache and preloading in production is a different world again from a CLI benchmark.
And treat a single red benchmark job as a signal to re-run before it is a signal to revert. If it fails twice, it is real.
Know what PHPBench cannot tell you#
A benchmark tells you that a number moved between two commits. It does not tell you where the time went, and it says nothing about behaviour under concurrency.
When the gate goes red and the diff is not obvious, the next tool is a profiler — SPX or Blackfire and a flame graph will show you the frame that grew. When the question is "does this hold up at 300 requests per second", that is a load test against a real environment, and neither a benchmark nor a profiler answers it.
Wrapping Up#
Start with one subject. Pick the class you already know is hot, get its rstdev under 2% locally, then put the gate in CI with a 10% band and leave it there for a fortnight before tightening anything. One honest benchmark that fails for real reasons is worth more than twelve that everyone has learned to re-run.
Once it is green and quiet, it belongs alongside the rest of your quality gates — see the complete Laravel developer toolchain for where it sits, and writing a custom PHPStan rule if you want the same kind of enforcement applied to conventions rather than speed.
FAQ#
What is PHPBench?
PHPBench is a benchmarking framework for PHP. It runs a method a configurable number of times, collects timing and memory samples across repeated measurements, and reports the distribution rather than a single number. Unlike a profiler, it can store results and assert against them, which is what lets it act as a test that fails a build.
How do I catch performance regressions in CI?
Run your benchmarks against the target branch first and store the result with --tag, then run them against the pull request with --ref pointing at that tag and an --assert expression comparing the current mode to the baseline mode within a percentage band. A failed assertion exits non-zero and fails the job. Do both runs on the same runner in the same job, or the comparison is meaningless.
How is PHPBench different from a profiler?
PHPBench answers "did this get slower between these two commits", by measuring one unit many times and comparing distributions. A profiler such as Blackfire or SPX answers "where is the time going in this one request", by instrumenting every function call in a single execution. You use PHPBench as a gate and a profiler as the investigation that follows when the gate trips.
How many revolutions and iterations should I use?
Choose revolutions so that one measured window lasts around a millisecond — for a method taking a few microseconds that is typically 500 to 5,000. Then use eight to ten iterations so there are enough samples to compute a stable mode. The number to judge it by is rstdev: under 2% is assertable, above 5% means the measurement is dominated by noise.
Can I benchmark Laravel code that needs the container?
Yes. Require bootstrap/app.php and call bootstrap() on the console kernel inside a #[Bench\BeforeMethods] hook, then resolve your subject out of the container there too. That keeps both the framework boot and the container resolution outside the measured window. Avoid benchmarking anything that hits the database or the network, because you will be measuring I/O rather than your code.
How do I stop benchmarks failing randomly on GitHub Actions?
Disable Xdebug with coverage: none, pin the PHP version and extensions, set --retry-threshold=5 so unstable iterations are resampled, use ten iterations instead of three, and keep the tolerance band at 10% or wider. Give the benchmark its own job so nothing else competes for CPU. Shared runners will never be stable enough for small regressions, so gate on large ones and accept the limit.