htop和golang readmemstats之间的差异

My program loads a lot of data at start up and then calls debug.FreeOSMemory() so that any extra space is given back immediately.

loadDataIntoMem()
debug.FreeOSMemory()

after loading into memory , htop shows me the following for the process

 VIRT    RES     SHR
 11.6G   7629M   8000

But a call to runtime.ReadMemStats shows me the following

Alloc         5593336608   5.3G
BuckHashSys   1574016      1.6M
HeapAlloc     5593336610   5.3G
HeapIdle      2607980544   2.5G
HeapInuse     7062446080   6.6G
HeapReleased  2607980544   2.5G
HeapSys       9670426624   9.1G
MCacheInuse   9600         9.4K
MCacheSys     16384        16K
MSpanInuse    106776176    102M
MSpanSys      115785728    111M
OtherSys      25638523     25M
StackInuse    589824       576K
StackSys      589824       576K
Sys           10426738360  9.8G
TotalAlloc    50754542056  48G
  1. Alloc is the amount obtained from system and not yet freed ( This is resident memory right ?) But there is a big difference between the two.
  2. I rely on HeapIdle to kill my program i.e if HeapIdle is more than 2 GB, restart - in this case it is 2.5, and isn't going down even after a while. Golang should use from heap idle when allocating more in the future, thus reducing heap idle right ?
  3. If assumption 1 is wrong, which stat can accurately tell me what the RES value in htop is.
  4. What can I do to reduce the value of HeapIdle ?

This was tried on go 1.4.2, 1.5.2 and 1.6.beta1

The effective memory consumption of your program will be Sys-HeapReleased. This still won't be exactly what the OS reports, because the OS can choose to allocate memory how it sees fit based on the requests of the program.

If your program runs for any appreciable amount of time, the excess memory will be offered back to the OS so there's no need to call debug.FreeOSMemory(). It's also not the job of the garbage collector to keep memory as low as possible; the goal is to use memory as efficiently as possible. This requires some overhead, and room for future allocations.

If you're having trouble with memory usage, it would be a lot more productive to profile your program and see why you're allocating more than expected, instead of killing your process based on incorrect assumptions about memory.