ProgramGuru

Memory Profiling

Start with Memory Profiling

In this lesson, explore memory profiling through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of memory profiling.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Memory profiles describe allocation sites and retained heap objects. The runtime/pprof tool and go test -memprofile help identify where memory is used.

Different views answer different questions: allocation totals show churn, while in-use objects show memory retained at the observation point.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for memory profilingAllocated bytes and retained bytes are different measures.Run workloadStep 1Record allocationsStep 2Inspect memory profileStep 3Reduce unnecessary workStep 4Allocated bytes and retained bytes are different measures.
Allocated bytes and retained bytes are different measures.

Tools, syntax and practical notes

Commands: go test -run ^$ -bench . -memprofile mem.out, then go tool pprof -alloc_space mem.out or the default heap view. See the runtime/pprof package.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func build(n int) []int {
	values := make([]int, 0, n)
	for i := 0; i < n; i++ {
		values = append(values, i)
	}
	return values
}
func main() { values := build(4); fmt.Println("Items:", values) }

Output

Items: [0 1 2 3]

Trace what the program does

The function preallocates capacity for four values and appends them. Its predictable result makes it a good starting point for comparing allocation patterns.

Avoid common mistakes

  • The size of one test slice does not predict production memory pressure.
  • An allocation profile differs from a heap-in-use profile.

Try it yourself

Benchmark build(1000) with and without preallocation and compare -benchmem and pprof.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What can a memory profile help identify?
Choose one answer. You can try again.

Answer and explanation

Allocation sources and retained heap usage

Correct. The function preallocates capacity for four values and appends them.

What you should remember

You have practiced Memory Profiling in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Fuzz Testing →