notexOPENOverview
Notex/Languages/Practice: Working with the Garbage Collector
04.19LESSON 19 OF 20 · 1 MIN READ

Practice: Working with the Garbage Collector

Always free to read

Now that you have learned about using pointers and memory effectively in Go, work through these exercises to reinforce your knowledge.

  1. Create a struct named Person with three fields: FirstName and LastName, of type string, and Age, of type int. Write a function called MakePerson that takes in firstName, lastName, and age and returns a Person. Write a second function MakePersonPointer that takes in firstName, lastName, and age and returns a *Person. Call both from main. Try to guess what escapes to the heap. Compile your program with go build -gcflags="-m". This both compiles your code and prints out which values escape to the heap. Are you surprised about what escapes? Why or why not?

  2. Write a program that builds a []Person with 10,000,000 entries. (They can all be the same names and ages.) See how long it takes to run. Then change the value of GOGC and see how that affects the completion time. Now set the environment variable GODEBUG=gctrace=1 to see when garbage collections happen. How does changing GOGC changes the number of garbage collections? What happens if you create the slice with a capacity of 10,000,000? Modify the program to build a slice of []*Person and see how that changes the behavior.

  3. Write a function that creates a []string of varying sizes. Use runtime.ReadMemStats to figure out the minimum capacity for a string slice to be allocated on the heap instead of the stack. (Hint: Check the number of Mallocs.)

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K