Analyze large allocations and fragmentation
Analyze large allocations and fragmentation
Large heap objects take page runs rather than small-class slots in Go 1.23. Fragmentation means memory is reserved or occupied in a way that prevents all of it from serving requested objects efficiently. A partly occupied span can retain unused slots; a free page run may be unsuitable for another request. HeapAlloc is bytes of allocated heap objects, including unreachable objects not yet freed; HeapInuse covers in-use spans. HeapInuse minus HeapAlloc is an upper bound estimate of space dedicated to classes but not used by objects, not a precise fragmentation diagnosis. HeapIdle minus HeapReleased estimates idle heap memory retained for reuse. Neither is process RSS.
package main
import ( "fmt")
func gap(total, used uint64) (uint64, bool) { if used > total { return 0, false } return total - used, true}func main() { a, ok := gap(8192, 6000) b, _ := gap(4096, 1024) fmt.Println(a, ok, b) _, ok = gap(2, 3) fmt.Println(ok)}These synthetic byte counts demonstrate subtraction with an explicit underflow guard. They do not measure real fragmentation. Use fields from the same ReadMemStats snapshot, not values taken at unrelated times. Inspect object lifetimes and profiles alongside the estimates.
Expected output:
2192 true 3072falseCopy a small retained result out of a large buffer
package main
import ( "fmt")
func prefix(src []byte, n int) ([]byte, error) { if n < 0 || n > len(src) { return nil, fmt.Errorf("invalid length") } return append([]byte(nil), src[:n]...), nil}func main() { big := make([]byte, 1<<20) copy(big, "Go!") small, e := prefix(big, 3) if e != nil { panic(e) } big[0] = 'X' fmt.Println(string(small), len(small))}A short subslice can keep an entire backing array reachable. Copying produces an independent backing array for the prefix; it may allocate, but can reduce retained memory once no other references to the original remain. A full slice expression limits capacity but does not detach storage. This example verifies independence, not immediate reclamation or a particular RSS drop.
Expected output:
Go! 3Try it locally
Return an independent copy of the last n bytes of an input; reject negative or oversized n. Test n=0, n=2 and n>length; mutate the original to verify independence.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime allocation 05: Analyze large allocations and fragmentation
Check the lesson objective before moving on.
What does HeapInuse minus HeapAlloc estimate?
Does reducing slice capacity detach its backing array?