How to set memory limit while running golang application in local system

Viewed 61

i want set heap size for go application in my windows machine

In java we used to provide -Xms settings as vm arguments in intellij but how to provide similar setting in golang and set memory limit for the go application.

Tried with

<env name="GOMEMLIMIT" value="2750MiB" />

but not working

we are using go 1.6.2 version.

1 Answers

Go 1.19 adds support for a soft memory limit:

The runtime now includes support for a soft memory limit. This memory limit includes the Go heap and all other memory managed by the runtime, and excludes external memory sources such as mappings of the binary itself, memory managed in other languages, and memory held by the operating system on behalf of the Go program. This limit may be managed via runtime/debug.SetMemoryLimit or the equivalent GOMEMLIMIT environment variable.

You can't set a hard limit as that would make your app malfunction if it would need more memory.

To set a soft limit from your app, simply use:

debug.SetMemoryLimit(2750 * 1 << 20) // 2750 MB

To set a soft limit outside of your app, use the GOMEMLIMIT env var, e.g.:

GOMEMLIMIT=2750MiB

But please note that doing so may make your app's performance worse as it may enforce more frequent garbage collection and return memory to OS more aggressively even if your app will need it again.

Related