Lazy Loading Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Lazy Loading runs in O(1) time and O(1) space, in Go as in every other language.
- ✓Memoisation lives in sync, in two generations. sync.Once with its single Do(func()) method is the original; Go 1.21 added sync.OnceFunc, sync.OnceValue[T] and sync.OnceValues[T1, T2], which wrap a function and return a memoised version, so the result no longer needs a companion struct field.
- ✓Anything producing a result belongs in the OnceValue family. The older sync.Once shape leaves the value in a plain struct field, and that field is readable without going through Do, which is exactly the race a reviewer scans for.
- ✓The Go trap: Once.Do and OnceValue disagree about panics, and the disagreement is documented rather than accidental.
- ✓The interesting cost here is construction, not steady state. OnceValue captures the memoised result and the once state inside the closure it returns, that capture escapes by definition, and it heap-allocates one closure per memoised function during package initialisation.
What Lazy Loading actually is
Lazy Loading in Go: what you actually reach for
Go implementation
package vm
import (
"fmt"
"regexp"
"sync"
)
// Package-level vars are the opposite of lazy: built before main runs.
var seed = map[string]byte{"nop": 0x00, "push": 0x10, "add": 0x20, "jmp": 0x30}
// sync.OnceValues (Go 1.21) memoises both results. If the body panics, the
// returned function re-panics with the same value on every later call.
var mnemonicRe = sync.OnceValues(func() (*regexp.Regexp, error) {
return regexp.Compile("^[a-z]{2,5}$")
})
// The pre-generics shape: Do takes func() and returns nothing, so the error
// has to ride on a companion field.
type Disassembler struct {
once sync.Once
table map[string]byte
err error
}
func (d *Disassembler) Table() (map[string]byte, error) {
d.once.Do(func() {
re, err := mnemonicRe()
if err != nil {
d.err = fmt.Errorf("mnemonic pattern: %w", err)
return
}
d.table = make(map[string]byte, len(seed))
for name, code := range seed {
if re.MatchString(name) {
d.table[name] = code
}
}
})
return d.table, d.err
}
// Pass this as *Disassembler only: copying it copies the Once into a fresh
// zero state and buys a second init. go vet's copylocks check catches that.
func New() *Disassembler { return &Disassembler{} }Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Lazy Loading?
Memoisation lives in sync, in two generations. sync.Once with its single Do(func()) method is the original; Go 1.21 added sync.OnceFunc, sync.OnceValue[T] and sync.OnceValues[T1, T2], which wrap a function and return a memoised version, so the result no longer needs a companion struct field. Everything else in the language pulls the opposite way: package-level var initialisers and func init() run before main in dependency order, so a blank import drags an entire initialisation graph into the process whether or not you call into it.
What is the most common Go mistake when implementing Lazy Loading?
Once.Do and OnceValue disagree about panics, and the disagreement is documented rather than accidental. Do guarantees f runs at most once, and it counts a panic as having run: the done flag is set, the deferred unlock releases, and every later caller returns immediately without invoking f. So if your initialiser panicked and something upstream recovered, the struct field it was meant to fill stays at its zero value forever and no call site ever sees an error. OnceValue and OnceValues took the opposite contract: they capture the panic and re-panic with the same value on every later call.
How does Lazy Loading actually perform in Go?
The interesting cost here is construction, not steady state. OnceValue captures the memoised result and the once state inside the closure it returns, that capture escapes by definition, and it heap-allocates one closure per memoised function during package initialisation. A sync.Once embedded in a struct instead adds a mutex and a flag inline, cheaper per instance but forcing pointer semantics on the whole type. Both settle to the same resting cost: an atomic load of the done flag and a well-predicted branch, with the mutex untouched after the first call. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.