Did you know that you can optimise memory by changing the order of struct fields in Go? Its fascinating! Right? I didn't know this until I saw this for myself in a reddit thread's example. Now this is not a new thing. Programming languages like C/C++ already has this concepts up and running for decades. Turns out, most processors access data more efficiently when data is aligned to certain byte boundaries (e.g., 2, 4, 8 bytes). For instance, an int64 (which is 8 bytes) is most efficiently accessed when stored at a memory address that is a multiple of 8. To achieve this alignment, Go automatically adds padding between fields in a struct. This padding can increase the size of a struct if fields are not ordered optimally. By ordering fields from largest to smallest, you minimise the amount of padding required between fields, resulting in a smaller overall memory footprint. Here are the links that where I found this: The Example: https://go.dev/play/p/MBXg4UBOerp The Thread: https://www.reddit.com/r/golang/comments/qcab7p/you_can_optimize_memory_by_changing_the_order_of/
Download the medial app to read full posts, comements and news.