Reviewer · Performance Optimization
Avoid unnecessary work
Eliminate redundant computation, allocation, and I/O on hot or frequently-executed paths. Specifically: 1. Cache/reuse expensive results instead of recomputing them in loops. For example, compile a regex once (e.g. with `sync.OnceValue`) and reuse the compiled matcher, rather than re-compiling it on every iteration or request.
Eliminate redundant computation, allocation, and I/O on hot or frequently-executed paths. Specifically:
- Cache/reuse expensive results instead of recomputing them in loops. For example, compile a regex once (e.g. with
sync.OnceValue) and reuse the compiled matcher, rather than re-compiling it on every iteration or request. - Skip work entirely when it provides no benefit. If a code path (e.g. mount manager activation for
overlayfs) is a guaranteed no-op for certain inputs, add an explicit fast-path that bypasses the extra RPCs/leases/locks. Document the trade-off with a comment (and a link to the discussion/rationale) when the check is a pragmatic hard-coded list rather than a fully general solution. - Order checks so cheap, likely-to-fail validations run before expensive operations (e.g. locking, DB/container lookups). Validate input up front to allow an early return before doing costly work:
func (daemon *Daemon) CheckpointCreate(name string, config checkpoint.CreateRequest) error { if err := validateCheckpointID(config.CheckpointID); err != nil { return err // cheap check first, before locking or fetching the container } ... } - Avoid sending/processing redundant data that will just be discarded downstream — e.g. don’t broadcast an event back to its own owner if the receiver will just lock and drop it; filter it out before adding to the work queue.
- Avoid unnecessary allocations when simpler alternatives exist, such as using
strings.SplitSeqinstead ofstrings.Splitwhen you only need to iterate over substrings and don’t need the full slice. - Don’t assume a data structure is “obviously” more efficient — benchmark it. For small/bounded sets, a linear
slices.Containsscan can consistently outperform a map lookup; verify the real-world size and use benchmarks to choose the right data structure instead of defaulting to maps for all lookups.
When submitting performance-sensitive changes, include a short rationale (and benchmark numbers where applicable) explaining why the chosen approach reduces allocations, lock contention, RPC calls, or redundant computation.