How to Preallocate Slices for Performance in Go

Preallocate Go slices using make with a capacity argument to reduce memory reallocations and improve performance.

Preallocate slices in Go by specifying the capacity in the make function to avoid memory reallocations during growth. This reduces CPU overhead from copying data to larger memory blocks as the slice expands.

// Preallocate a slice with a known capacity of 100
items := make([]string, 0, 100)

// If you know the exact final size, set length and capacity
items = make([]string, 100)

In the standard library's archive/zip package, this is done safely by validating the expected count against the file size before allocation to prevent malicious archives from causing out-of-memory errors:

// From archive/zip/reader.go: init()
if end.directorySize < uint64(size) && (uint64(size)-end.directorySize)/30 >= end.directoryRecords {
    r.File = make([]*File, 0, end.directoryRecords)
}