Chapter 11. Optimization Patterns
With all we’ve learned from the past 10 chapters, it’s time to go through various patterns and common pitfalls I found when developing efficient code in Go. As I mentioned in Chapter 10, the optimization suggestion doesn’t generalize well. However, given you should know at this point how to assess code changes effectively, there is no harm in stating some common patterns that improve efficiency in certain cases.
Be a Mindful Go Developer
Remember that most optimization ideas you will see here are highly deliberate. This means we have to have a good reason to add them as they take the developer’s time to get right and maintain in the future. Even if you learn about some common optimization, ensure it improves efficiency for your specific workload.
Don’t use this chapter as a strict manual but as a list of potential options you did not think about. Nevertheless, always stick to the observability, benchmarking, and profiling tools we learned in previous chapters to ensure the optimizations you do are pragmatic, follow YAGNI, and are needed.
We will start with “Common Patterns”, where I describe some high-level optimization patterns we could see from optimization examples in Chapter 10. Then I will introduce you to the “The Three Rs Optimization Method”, an excellent memory optimization framework from the Go (and Prometheus) community.
Finally, in “Don’t Leak Resources”, “Pre-Allocate If You Can”, “Overusing Memory with Arrays”, and “Memory Reuse ...
Get Efficient Go 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.