Incremental concatenation vs array-and-implode string assembly
A controlled comparison of two common ways to assemble a few hundred text fragments in PHP.
Question and test setup
For a moderate output buffer, does collecting fragments and calling implode outperform repeated concatenation?
Results may be closer than folklore suggests because modern PHP optimizes common concatenation patterns; temporary-array allocation can offset implode benefits.
Template engines, exporters and log formatters often build strings in loops. Developers sometimes replace readable code based on assumptions inherited from other runtimes.
The correct choice should consider memory, streaming needs and code clarity, not only a micro-level timing result.
The measured gap
What this run shows: Incremental concatenation recorded the lower median for this string shape. Allocation pattern and final output size should be checked in the real builder before refactoring. The slowest-to-fastest median spread was 2.28% on the measured host.
| Variant | Median | Middle 50% | Operations/s | Additional measure |
|---|---|---|---|---|
| Incremental concatenationFastest | 46.59 µs | 46.23 µs–49.75 µs | 21,463 | — |
| Array plus implode | 47.66 µs | 44.83 µs–48.34 µs | 20,984 | — |
What the numbers suggest
A measured difference here describes this fragment count and size. It does not imply that buffering a very large export in memory is safe.
When output can be streamed, streaming may dominate both tested choices by reducing peak memory and time-to-first-byte. For modest in-memory strings, readability and maintainability are often decisive.
When the difference is worth acting on
- Keep the clearer implementation until a profile identifies string assembly as material.
- Use streaming writers for unbounded exports rather than scaling either in-memory pattern indefinitely.
- Repeat with real fragment sizes before changing production rendering code.
Repetition and environment
- Both variants generate the same 350 lines from the same integer sequence.
- The concatenation variant appends directly; the second stores fragments and joins them once.
- The final byte length is consumed to prevent an unused result.
Open measured environment
- Measurement run
- 2026-07-22T15:23:56+00:00
- PHP
- 8.4.23 (cli)
- Operating system
- Linux 4.18.0-553.85.1.el8_10.x86_64
- Architecture
- x86_64
- Processor
- AMD EPYC-Rome Processor
- Reported host memory
- 15.02 GiB host total
- CLI OPcache
- 0
- PHP memory limit
- 1024M
- Loaded study extensions
- json, openssl, zlib, mbstring, pdo_sqlite
- Timing clock
- hrtime(true)
- Measured rounds
- 7
Reasons the ranking may move
- Peak memory is not independently measured in this study.
- Interpolation, multibyte transformation and template-engine overhead are excluded.
Primary documentation
These sources describe the PHP functions under test. The performance ranking comes only from this published fixture and environment.