There are other nuances one should consider.

Potential dangers of storing structs rather than pointers: If other code can have a reference to MyStruct one must consider that array length changes can relocate each MyStruct, potentially leading to multiple outstanding copies with different values. (That’s bad.) The typical solutions are (1) manage the lifetime of references to not overlap with slice size changes; (2) have the slice contain pointers to MyStruct instead of the value; (3) have references use an index instead of a pointer. Indexes and offsets should be used for relocatable storage.

Here is a demonstration of the problem: https://play.golang.org/p/lk7s0IO7-WY
Additional advantages of storing structs rather than pointers: There are benefits beyond the allocation savings the author describes and measures. Indexes can provide great space savings over pointers in some circumstances. For example if there are only 255 entries one could use a 1-byte uint8 for the index instead of a 8-byte (*MyStruct). In some projects this can be a huge memory savings.
The locality of reference is another advantage. In the example assuming MyStruct is 8 bytes and 64 byte cache lines, a scan of slice values can touch 8 entries per cache line instead of potentially less than 1 entries per cache line.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store