Avoid unnecessary memory allocations in performance-critical code paths, especially in frequently executed functions or loops that process large datasets. Common allocation sources to eliminate include:
Example of eliminating intermediate slice:
// Before: Creates unnecessary intermediate slice
proxyAddrs := make([]string, 0, len(proxyServers))
for _, proxyServer := range proxyServers {
proxyAddrs = append(proxyAddrs, proxyServer.GetPublicAddr())
}
for _, proxyAddr := range proxyAddrs {
// process proxyAddr
}
// After: Direct iteration
for _, proxyServer := range proxyServers {
proxyAddr := proxyServer.GetPublicAddr()
// process proxyAddr directly
}
Example of avoiding fmt.Sprintf in index functions:
// Before: Expensive formatting in frequently called function
return fmt.Sprintf("%s/%s", date.Format(time.RFC3339), name)
// After: Direct string concatenation
return date.Format("20060102") + "/" + name
This optimization is particularly important for functions called frequently, index operations on large collections, or code paths processing thousands of items.
Enter the URL of a public GitHub repository