Pointer Performance

New developers often assume pointers are always faster because they “avoid copying.” In Go, the reality is more nuanced due to how memory is managed.

Stack vs. Heap

  • Stack: Very fast. Local, non-pointer variables are usually stored here.
  • Heap: Slower. Variables that “escape” their function (often by being pointed to) are moved to the heap, which requires garbage collection.

Copying is Cheap

For small data (ints, small structs), copying the value on the stack is often faster than the overhead of managing a pointer on the heap.

Rule of Thumb

  1. Clarity First: Use pointers when you need a shared reference. Use values otherwise.
  2. Only Optimize if Needed: Don’t use pointers for performance unless you have a benchmark proving that copying is the bottleneck.
  3. Large Data: Once a struct becomes large enough (e.g., dozens of fields), the cost of copying might justify using a pointer.