Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Lazy Loading Implementation in Go

11 min readbeginner
Website QA and SEO audits

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 defers the cost of building something until the first caller actually needs it: a parsed rule table, a compiled pattern, a database handle, or a megabyte of code that most sessions never execute. The mechanics look trivial. Check whether a slot is empty, fill it, hand it back. That apparent simplicity is exactly why it stays a durable source of subtle bugs. Two threads can arrive at the empty slot together. A memory model can let one of them publish the reference before the object's own field writes become visible to the other, which is what turns naive double-checked locking into a correctness defect rather than a style preference. A factory that throws leaves a third state, neither empty nor filled, and every runtime answers it differently: retry on the next call, cache the failure permanently, or quietly mark the work done and hand out a zero value. Deferring also moves work rather than deleting it, so one unlucky request pays a latency spike the next thousand do not. The eight implementations here disagree at nearly every level. Four hand you a dedicated once-token in the standard library, and hand-rolling your own there is a review failure. Two make global laziness a language guarantee you cannot switch off, so the whole singleton pattern collapses into one keyword. One erases its lazy declarations entirely at compile time, leaving the emitted behaviour hostage to a compiler flag most teams set once and never read again. One treats a failed initialisation as permanent corruption of the type itself. Two stack a second, unrelated flavour of laziness on top: deferring delivery of the code across a network boundary, with its own syntax and its own failure modes. The big-O is identical everywhere. Almost nothing else is.

Lazy Loading in Go: what you actually reach for

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.

Go implementation

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 other standing rule is that any type containing a sync.Once travels by pointer only. sync.Once embeds a mutex, so go vet's copylocks analysis flags the copy, and go vet wired into CI is what stands between you and a silently duplicated initialisation.
go
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 Free

The Go-specific trap

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.

Performance in Go, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Lazy Loading between languages.

Real-World Applications

Lazy Loading is used extensively in production software: web frameworks, content management systems, API gateways, and SPA architectures implement this pattern for handling HTTP requests and rendering. In Go specifically, the standard library and popular packages like gin and gorm apply these principles. Understanding Lazy Loading helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Lazy Loading appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Lazy Loading over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Lazy Loading to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Want 50 audits a day? Explore SeekerPro

Engagement

0

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.