A
A
Alexey2018-06-20 12:54:20
go
Alexey, 2018-06-20 12:54:20

Why is Go-webserver eating so much memory and not freeing it?

Wrote a web server in Go
Accepts a GET parameter and collects a large array

package main

import (
  "net/http"
  "fmt"
  _ "net/http/pprof"
  "strings"
)
func one(w http.ResponseWriter, r *http.Request){
  s := r.URL.Query().Get("s")

  array := []string{}
  for i:=0; i<10000; i++{
    new_s := strings.Repeat(s,1000) // Если вынести за пределы цикла  - потребляет меньше памяти (35мб) но все равно ее не освобождает
    array = append(array, new_s)
  }
  w.Write([]byte("ok"))

}
func main(){
  http.HandleFunc("/one", one)
  fmt.Println("ready")
  server := &http.Server{Addr: ":8008"}
  server.ListenAndServe();
}

At startup, it takes 6 MB of RAM.
At startup: - memory consumption grows to 10mb ~ 30mb ~ 800mb And in all cases it is not released in any way. The process continues to take up a lot of memory Who can tell me what's wrong here? Otherwise, I don’t understand why it takes up so much memory and does not release it even when the client’s request is processed?
ab -n 1000 -c 100 "http://localhost:8008/"
ab -n 1000 -c 1 "http://localhost:8008/one?s=1"
ab -n 1000 -c 100 "http://localhost:8008/one?s=1"

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2018-06-20
@babderos

After garbage collection, the memory is not immediately returned to the OS, because if the load suddenly starts again, it will be faster to reuse the memory already allocated by the application than to ask the OS again for it.
If the load is absent for a long time, the goshka must eventually give the memory to the OS.
This can be done manually via debug.FreeOSMemory()

E
evgensoft, 2018-06-20
@evgensoft

As it has already been written above - indeed, the memory is not given immediately, but, if possible, is reused.
Those. with intensive work, it will no longer grow, and if it is not needed for a long time, it will be released.
You can manually call garbage collection - runtime.GC()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question