9.5 Lazy Initialization: sync.Once
It is good practice to defer an expensive initialization step until
the moment it is needed.
Initializing a variable up front increases the
start-up latency of a program and is unnecessary if execution
doesn’t always reach the part of the program that uses that variable.
Let’s return to the icons
variable we saw earlier in the chapter:
var icons map[string]image.Image
This version of Icon
uses lazy initialization:
func loadIcons() { icons = map[string]image.Image{ "spades.png": loadIcon("spades.png"), "hearts.png": loadIcon("hearts.png"), "diamonds.png": loadIcon("diamonds.png"), "clubs.png": loadIcon("clubs.png"), } } // NOTE: not concurrency-safe! ...
Get The Go Programming Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.