S
S
Skelman2019-07-25 08:48:23
go
Skelman, 2019-07-25 08:48:23

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
}

And every time I go to localhost:8080/ping, the volume of RAM usage increases greatly, which should be cleared over time, but this does not happen. Who knows how to deal with this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Shitskov, 2019-07-25
@Zarom

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

A
Andrey Tsvetkov, 2019-07-25
@yellow79

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

A
Alexander Pavlyuk, 2019-07-25
@pav5000

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 question

Ask a Question

731 491 924 answers to any question