Garbage collector

I have global map duplcates, I am running the map inside a for loop and each time I do
duplcates = make(map[int]bool). I want to know if the previous memory of the map is free when we do duplcates = make(map[int]bool) again?

Hi and welcome! So you’re doing something like this:

package main

var duplicates = make(map[int]bool)

func main()  {
	for {
		duplicates = make(map[int]bool)

Well, in this case GC will allocate the minimal amount of memory necessary for a map (the root of the hash map only) each time, and it will release each allocation in form of bunch, since GC runs at a specific time “periodically” (see the GC algorithm). So the answer is no, not each time, it would be too expensive.

I tested it with heap and trace pprof and from what I can tell, memory will be reused and GC calls were not very expensive. The code. I used map with 100000 elements, without changing the size dynamically. But as you can see from the heap analyse:

the space itself was not too much. And if we have a look on the trace, the heap size stays permanent, which suggests, that GC collecting memory very efficiently.
I gathered statistics within 60 seconds usage of the program. Average GC runtime is 1,968,642 ns on my machine and imho it is also not too much.
To sum this up, the memory allocated for your map will be reused on every make call. I would suggest if you know approximate size of the map, pass its size into the make call.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.