Simple techniques to optimise Go programs

Simple techniques to optimise Go programs

See a Twitter thread from Damian Gryski for an interesting example where removing strings from a large map in favour of a smarter data structure actually increased memory. This has two downsides:

The below program shows the difference in performance:

We can see that the version is 3.5x faster, results in 1/3rd the number of allocations, and half the memory allocated. When you reach the of a slice, a new array with double the cap of the previous slice is allocated, the memory is copied over from the old slice to the new one, and the old array is discarded

I often see code like the following that allocates a slice with zero capacity, when the capacity of the slice is known upfront.

Source: stephen.sh