Junior — Middle
Share your experience in identifying and fixing memory leaks in applications using profiling tools.
sobes.tech AI
Answer from AI
To detect and fix memory leaks in Go, I use built-in profiling tools such as pprof.
Process:
- Enable memory profiling in the application:
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// other code
}
- Run the application and collect the memory profile using the command:
go tool pprof http://localhost:6060/debug/pprof/heap
-
Analyze the report to find objects that occupy a lot of memory and are not released.
-
Check the code for retained references that prevent the garbage collector from freeing memory.
-
Make changes, such as nullifying references, using
runtime.SetFinalizer, or optimizing data structures. -
Repeat profiling to ensure the leak is fixed.
This approach allows effective detection and fixing of memory issues in Go applications.