Rust Lazy Statics, Measured: OnceLock vs LazyLock vs lazy_static — and the 2x Claim That Does Not Reproduce
If you write Rust, you have a lazy static somewhere: a compiled regex, a config map, a logger. Three mechanisms compete for the job — std::sync::OnceLock (stable since 1.70), std::sync::LazyLock (stable since 1.80), and the lazy_static crate that most codebases still carry — and the guides that rank them disagree by a factor of two.
The loudest claim, repeated twice on one page, is that OnceLock is "2x faster than lazy_static." A second guide says LazyLock is "5-10% faster access in high-contention scenarios due to optimized deref." A third, from 2022, measured all three at 26–27 ns per iteration and concluded the choice hardly matters. None of the three shows a methodology.
What this guide is
This guide is a measurement, not a recommendation. It reports two numbers per mechanism:
- ACCESS — steady-state cost per access, after initialization is done. This is the cost every call pays, forever, and the one that matters most: initialization happens once, access happens on every request.
- INIT — wall time from spawning N threads until the last thread has made its first access, with initialization triggered on that first access. This is the cost of the cold path, when several threads arrive before the value exists.
The workload is deliberately bare: an AtomicUsize cell with the primitive's own access pattern, 10 million accesses per rep in the ACCESS job, so the measurement isolates the primitive instead of measuring the work it guards.
The headline: 1.24x, not 2x
Key result: OnceLock is 1.24x faster than lazy_static in steady-state access — not 2 times. LazyLock is 1.20x slower than OnceLock and only 2.7% faster than lazy_static, which is inside rep-to-rep spread. The first init has no consistent winner: each arm wins at one thread count, and at 32 threads all three sit within 4.6% of each other. The choice that matters is not speed — it is LazyLock's unrecoverable poisoning, which the next section covers.
| Mechanism | ACCESS, ns per access (median of 3 reps) | vs OnceLock |
|---|---|---|
std::sync::OnceLock |
1.121 (1.147 / 1.121 / 1.120) | 1.00x |
std::sync::LazyLock |
1.349 (1.418 / 1.349 / 1.348) | 1.203x slower |
lazy_static 1.5.0 |
1.386 (1.405 / 1.353 / 1.386) | 1.236x slower |
| Mechanism | INIT wall, N=2 (ns) | INIT wall, N=8 (ns) | INIT wall, N=32 (ns) |
|---|---|---|---|
std::sync::OnceLock |
110,844 | 342,890 | 1,423,667 |
std::sync::LazyLock |
91,817 | 418,705 | 1,436,840 |
lazy_static 1.5.0 |
88,998 | 425,704 | 1,488,673 |
Max/min spread across arms at each N: 1.245x at N=2, 1.242x at N=8, 1.046x at N=32.
Every rep in the ACCESS job returned the same total sum (14144381271541939712), so all three arms did the same work — the 0.26 ns gap between OnceLock and lazy_static is the primitive, not a different workload. The first rep was the slowest in every arm (warm-up: OnceLock 1.147 then 1.121, 1.120), so the medians above are the stable numbers, not the first-run ones.
What each mechanism actually is
OnceLock is a thread-safe cell that holds a value set exactly once, stabilized in Rust 1.70. It is a static-friendly OnceCell: you declare static RE: OnceLock<Regex> = OnceLock::new(); and call get_or_init on first use. get() never blocks — it returns None if the cell is uninitialized or still being initialized — and get_or_init runs exactly one initializer, with other threads waiting. If the initializer panics, the cell stays uninitialized and the next call retries; there is no poisoning. The docs warn that reentrant initialization from inside the closure is an error whose exact outcome is unspecified (the current implementation deadlocks).
LazyLock, stabilized in Rust 1.80, is the ergonomic sibling: static COUNTER: LazyLock<Mutex<i32>> = LazyLock::new(|| Mutex::new(0)); and then you just deref it — no explicit get_or_init call. The trade is in the docs, not in the benchmarks: poisoning is unrecoverable. If the init closure panics, the lock is poisoned and all future accesses panic. That is the sharpest behavioral difference among the three, and it is bigger than the 0.23 ns access gap.
lazy_static is the crate that predates both: lazy_static! { static ref RE: Regex = Regex::new(r"\d+").unwrap(); }. Version 1.5.0 has zero dependencies. Its Deref implementation runs an atomic check on every access — the crate's own docs describe a hidden static guarded by an atomic check per access — which is where its 0.26 ns gap comes from. It is the only one of the three that needs a crate at all; the other two are in std.
The published claims, tested
Claim 1: "OnceLock is 2x faster than lazy_static." Does not reproduce. One guide states it twice — "Prefer OnceLock over lazy_static for 2x speed in benchmarks" and, in its FAQ, "stable, 2x faster than lazy_static" — with no benchmark, no reps, no workload anywhere on the page. The measurement says 1.24x in steady-state access (1.386 vs 1.121 ns). A 2x claim would need lazy_static at about 2.24 ns; it measures 1.386. The claim overstates the gap by roughly four times in ratio terms. The direction is right — OnceLock is faster — and the size is wrong.
Claim 2: "LazyLock shows 5-10% faster access in high-contention scenarios due to optimized deref." Does not reproduce as a general statement. A second guide asserts this, again with no benchmark attached. The measurement says the sign of the gap flips with the job and the thread count:
- Steady-state access:
LazyLockis 20.3% slower thanOnceLock(1.349 vs 1.121 ns) — the opposite direction. - First init at N=2:
LazyLockis 17.2% faster thanOnceLock(91,817 vs 110,844 ns). - First init at N=8:
LazyLockis 22.1% slower thanOnceLock(418,705 vs 342,890 ns). - First init at N=32:
LazyLockis 0.9% slower — inside noise.
"5-10% faster in high-contention scenarios" is underspecified — faster than what, on what job? — and no reading of the measurement supports it as a general claim. The honest statement is that LazyLock and OnceLock trade the lead with thread count, and the gap is small either way.
Claim 3: all three at 26–27 ns per iteration, choice hardly matters. Reproduces in direction, not in number — and the number is the tell. A 2022 measurement by rimutaka ran a regex::is_match workload through all three mechanisms and recorded 26–27 ns per iteration for every arm, concluding lazy_static "is fine" and once_cell "may be better for new projects." The 27 ns was the regex call, not the primitive: the primitive's ~1 ns is invisible inside a 27 ns workload. My probe measures the bare access with black_box reads and sees 1.121–1.386 ns. The 2022 result is consistent with mine — the primitive is a rounding error next to real work — but it could not have distinguished the three mechanisms, because it was measuring the regex. If your guarded workload costs 27 ns, the primitive's 0.26 ns gap is 1% of your per-call cost. If it costs 1 ns, the gap is 20%.
Claim 4, in passing: "OnceLock is zero-cost." The same guide calls OnceLock "zero-cost." Nothing is zero-cost: the measured steady-state access is 1.121 ns. "Zero-cost" here means "no extra allocation and no lock on the fast path," which is true — and worth stating precisely, because the number is small but not zero.
Trap 1: LazyLock poisoning is unrecoverable
The docs for LazyLock say it plainly, and it is the one difference in this guide that can break a program rather than slow it: if the initialization closure panics, the lock is poisoned, and all future accesses panic. There is no recovery path. Contrast the other two:
OnceLock: a panickingget_or_initleaves the cell uninitialized. The next call retries the initializer. No poisoning, ever.lazy_static: initialization runs understd::sync::Oncesemantics; a panicking initializer poisons theOnce, and later accesses panic — the same failure mode asLazyLock, documented in the crate's behavior.
LazyLock is the ergonomic choice — *COUNTER instead of get_or_init — and its failure mode is the harshest. If your initializer can panic (a Regex::new that fails, a config parse, a file read), OnceLock retries and LazyLock bricks the static for the life of the process. The probe's initializer never panics, so this is stated from the docs, not measured — but it is the difference that decides the choice for anything whose init can fail.
Trap 2: get() never blocks, and reentrant init deadlocks
OnceLock::get() looks like the cheap read path, and it is — but it returns None while another thread is still initializing. If you call get() on a cell whose initializer is running, you get None, not a wait. Code that treats None as "not yet configured" will misbehave on the cold path. The probe's ACCESS job forces initialization first and only then calls get(); the INIT job uses get_or_init, which is the blocking call.
The second half of the trap is reentrant initialization. The OnceLock docs state that initializing a cell from inside its own initializer is an error, the exact outcome is unspecified, and the current implementation deadlocks. LazyLock has the same shape: deref during init is a deadlock. If your initializer touches another lazy static that touches the first, the program hangs with no error. lazy_static's Deref has the same hazard. This is not a performance question — it is a hang, and it is the same in all three.
Trap 3: measure the primitive, not the work it guards
The 2022 result above is the cautionary tale: a 27 ns regex workload made three mechanisms that differ by 0.26 ns look identical, because the workload was 100x the difference. The same trap runs in reverse — a benchmark that reports a 2x gap between primitives is usually measuring something else (allocation, a lock, a branch prediction miss) and attributing it to the primitive.
Three rules the probe follows, and that any rerun should keep:
- Bare access,
black_boxapplied. The ACCESS job reads anAtomicUsizethrough the primitive's own access pattern, 10 million times per rep, withstd::hint::black_boxon the read so the compiler cannot fold the loop away. The identical sum across all nine runs (14144381271541939712) proves the work was identical. - Three reps, report the median. The first rep is the slowest in every arm — warm-up is real, and a single-rep benchmark reports the warm-up, not the steady state.
- Separate the cold path from the hot path. INIT wall time is ~99% thread wake and scheduling, not the primitive: the init work is about 1 µs while the walls run 89 µs to 1.5 ms. At N=32 the three arms sit within 4.6% because the primitive's contribution is inside scheduling noise. Reporting INIT and ACCESS as one number hides both.
Checklist
- [ ] If your initializer can panic, use
OnceLock: a failed init retries instead of bricking the static.LazyLockpoisoning is unrecoverable. - [ ] If you call
get()onOnceLock, handleNone— it means "initializing now," not "never configured." Useget_or_initwhen you need to wait. - [ ] Never initialize a lazy static from inside its own initializer, in any of the three mechanisms. The current implementations deadlock.
- [ ] Do not pick on the 2x claim. The measured gap is 1.24x steady-state, and it is 0.26 ns per access — invisible next to any real workload.
- [ ] Do not pick on the 5-10%
LazyLockclaim either. The measured gap flips sign with thread count and job; at N=32 the three arms are within 4.6%. - [ ] If you are still on
lazy_static, the migration case is the dependency, not the speed:OnceLockandLazyLockare instdsince 1.70 and 1.80, and the only remaining advantage oflazy_static1.5.0 isno_stdsupport. - [ ] When you benchmark a primitive, make the workload bare, apply
black_box, run three reps, and report the median — a single rep reports warm-up, and a 27 ns workload reports the workload.
Related guides on this site
- How Fast Do std::latch and std::barrier Wake Threads? Measured — 9 to 68 Times Faster Than a Condition Variable — the same three-rep discipline applied to C++20 synchronization primitives, where the measured gap is 9–68x and the published claim was ~2x in the other direction.
- Tokio Backpressure: Bounded Channels and Semaphore-Limited HTTP Fan-Out — another Rust measurement, on async channel backpressure rather than statics.
Sources
- Rust std, OnceLock — stabilized 1.70.0;
get()never blocks;get_or_initruns one initializer; init panic leaves the cell uninitialized and retryable; reentrant init is an error that currently deadlocks. - Rust std, LazyLock — stabilized 1.80.0; deref blocks during init; poisoning is unrecoverable — an init panic makes all future accesses panic.
- rimutaka, Rust's lazy_static! usage benchmarks and code deep dive — 2022-04-02; cargo +nightly bench on a regex
is_matchworkload: lazy_static 26–27 ns/iter, once_cell_lazy 26, vanilla 27; once_cell "~20% faster in a 32-thread test"; "lazy_static! is fine, but once_cell may be better for new projects." - CopyProgramming, Mastering Static Initialization Patterns in Modern Programming — "Prefer
OnceLockoverlazy_staticfor 2x speed in benchmarks"; FAQ: "stable, 2x faster than lazy_static." No benchmark, reps, or workload shown. - CopyProgramming, Rust Cookbook: Creating a Global Mutable Singleton in 2026 — "In 2026 benchmarks, LazyLock shows 5-10% faster access in high-contention scenarios due to optimized deref." No benchmark, reps, or workload shown.