Deduplicating repeated strings with array_unique or a keyed set
A same-input comparison of PHP’s built-in array_unique and an explicit keyed-set pass.
Question and test setup
Which approach is more efficient for removing repeated string identifiers while preserving a usable result?
The built-in function may benefit from optimized internal implementation, while an explicit set can make intent and later membership reuse clearer.
Import pipelines and event aggregation frequently receive repeated identifiers. The chosen approach can also affect key preservation and output ordering.
Semantic differences matter: array_unique preserves the first occurrence’s original key, whereas a keyed set naturally produces identifiers as keys.
The measured gap
What this run shows: array_unique completed this deduplication fixture sooner, while order preservation and key semantics determine whether it is a valid substitute. The slowest-to-fastest median spread was 139.92% on the measured host.
| Variant | Median | Middle 50% | Operations/s | Additional measure |
|---|---|---|---|---|
| array_uniqueFastest | 48.94 µs | 48.83 µs–51.77 µs | 20,434 | — |
| Keyed set | 117.41 µs | 116.72 µs–118.57 µs | 8,517 | — |
What the numbers suggest
A performance result is valid only after confirming that both output shapes fit the caller. Reindexing, preserving first-occurrence keys or returning a membership map can change the surrounding work.
When deduplication is followed by many membership checks, a keyed set may avoid a second conversion even if its isolated pass is not the fastest.
When the difference is worth acting on
- Define required ordering and key semantics before choosing the implementation.
- Prefer the built-in function when its exact output contract matches the use case.
- Prefer a keyed set when the result will also serve as a membership index.
Repetition and environment
- The fixture contains 6,000 strings drawn deterministically from 1,700 unique values.
- Both variants report the final unique count; they do not normalize case or Unicode.
- The explicit-set variant assigns each string as an associative key.
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
- Only strings are tested; mixed PHP values invoke different comparison behavior.
- Case folding and locale-aware normalization are outside scope.
Primary documentation
These sources describe the PHP functions under test. The performance ranking comes only from this published fixture and environment.