C
C
calculator2122021-07-26 17:06:03
go
calculator212, 2021-07-26 17:06:03

Why is it impossible to free memory in the program?

In general, I can not fully figure out how the release of memory works. I first fill the memory with an array of several megabytes, then I clear it and call the GC, but the size of the allocated memory remains the same. I read the answer to a similar question here , but I still don't understand if a program takes a few gigabytes and frees them in this way, will another program be able to use this memory if necessary?

package main

import (
  "fmt"
  "runtime"
  "time"
)

func fillA()[]int{
  a := make([]int, 999999)
  for i := 0; i < 999999;i++ {
    a[i]=i
  }
  return a
}

func main() {

  PrintMemUsage()

  var overall [][]int
  for i := 0; i<4; i++ {


    overall = append(overall, fillA())

    // Print our memory usage at each interval
    PrintMemUsage()
    time.Sleep(time.Second*1)
  }

  // Clear our memory and print usage, unless the GC has run 'Alloc' will remain the same
  overall = nil
  PrintMemUsage()
  fmt.Println("nil")
  time.Sleep(time.Second*5)
  // Force GC to clear up, should see a memory drop
  runtime.GC()
  fmt.Println("nil 2")
  time.Sleep(time.Second*5)
  PrintMemUsage()
}

func PrintMemUsage() {
  var m runtime.MemStats
  runtime.ReadMemStats(&m)
  fmt.Printf("Alloc = %v MiB", bToMb(m.Alloc))
  fmt.Printf("\tTotalAlloc = %v MiB", bToMb(m.TotalAlloc))
  fmt.Printf("\tSys = %v MiB", bToMb(m.Sys))
}

func bToMb(b uint64) uint64 {
  return b / 1024 / 1024
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shitskov, 2021-08-01
@calculator212

https://golang.org/doc/go1.12#runtime
You can read about MADV_FREE there.
Those. the default behavior frees the memory, but the kernel does not take the freed memory if it is not needed. I propose to conduct a test by disabling this flag. In that case, I believe the memory will be returned immediately.
I don't know the details of why you need to optimize memory performance. I would not embark on this process without specific reasons.
This flag will affect performance, so if the host doesn't need the memory immediately, don't force it back.
You should monitor host and application metrics, have alerts for deviations from the norm, and only in cases of deviation start optimizing the operation of application components and OSes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question