Why simple Go app consume high memory usage

Issue

this is very simple app :

package main
import "fmt"
func main() {

    for i:= 0; i < 100000; i++ {
        go func (){
            fmt.Println("hello message.")
        }()
    }

    fmt.Scanln()
    fmt.Println("done")
}

after run application on windows, and look at the windows task manager I saw this state:

go app state

someone can say why?

Solution

Launched goroutines run concurrently, independent of each other. It’s the responsibility and duty of the goroutine scheduler to handle them.

A goroutine is a lightweight thread: it costs a lot less than an OS thread, but still costs something. Initial stack for a new goroutine is a couple of KBs (around 8KB), and grows / shrinks as needed. See Goroutines 8kb and windows OS thread 1 mb.

Given that you launch 100,000 goroutines without any synchronization, it may very well be that you will have 100,000 goroutines running before any of them finishes. Estimated memory requirement for that would be:

100,000 * 8KB = 800 MB

So your app using 884MB is pretty much in line with the estimation.

Answered By – icza

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.