Answer the question
In order to leave comments, you need to log in
Why is golang not clearing memory?
I recently started learning golang and ran into a behavior of a slice of structures that was not entirely clear to me.
Here is a simple code for example
package main
import "github.com/gin-gonic/gin"
type user struct {
ID int
Name string
}
func main() {
findUser()
r := gin.New()
r.Use(gin.Recovery())
r.GET("/ping", func(c *gin.Context) {
a := findUser()
c.JSON(200, gin.H{
"message": a,
})
})
r.Run()
}
func findUser() int {
var users []*user
for i := 0; i < 100000; i++ {
users = append(users, &user{
ID: i,
Name: "ololo",
})
}
length := len(users)
var u []*user
users = u
return length
}
Answer the question
In order to leave comments, you need to log in
Everything is fine with GC in go. The memory is cleared, not returned to the system, but reused by the program as long as there is enough free memory in the system.
And what is this and why?
var u []*user
users = u
The memory is cleared by GC, everything is fine, you don't have to worry. It's just that what is cleared is not returned to the system. After some time, the goshka will return this data back, you just need to wait. Maybe 10 minutes, maybe an hour, maybe more, this time is not regulated by anything
First, reduce the number of allocations by immediately creating a slice of the desired length.
Instead var u []*user
, use
Second, what version of Go do you have? On 1.12.1 I was not able to reproduce such a sharp increase in memory. users := make([]*user, 0, 100000)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question