Identify and eliminate computationally expensive operations in frequently executed code paths. Common expensive operations include repeated computations, unbounded API calls, inefficient string operations, and operations that don’t scale with data size.
Key strategies to avoid expensive operations:
Example optimization for string building:
// Expensive: fmt.Sprintf with multiple allocations (317ns, 5 allocs)
func getEndpointKey(portName string, portNum int32, ips []string) string {
ipString := strings.Join(ips, ", ")
return fmt.Sprintf("%s-%s-%d", ipString, portName, portNum)
}
// Optimized: strings.Builder with fewer allocations (75ns, 2 allocs)
func getEndpointKey(portName string, portNum int32, ips []string) string {
var b strings.Builder
for k, ip := range ips {
if k > 0 {
b.WriteString(", ")
}
b.WriteString(ip)
}
b.WriteString("-")
b.WriteString(portName)
b.WriteString("-")
b.WriteString(strconv.Itoa(int(portNum)))
return b.String()
}
Always consider the performance impact of operations in hot paths and prefer efficient alternatives that scale well with system load.
Enter the URL of a public GitHub repository