Advertisement
cydside

Optimized struct

Feb 25th, 2023 (edited)
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.70 KB | None | 0 0
  1. /*
  2. int/uint
  3.     either 32 bits (4 bytes) or 64 bits (8 bytes)
  4. int8/uint8
  5.     8 bits (1 byte)
  6. int16/uint16
  7.     16 bits (2 bytes)
  8. int32/uint32
  9.     32 bits (4 bytes)
  10. int64/uint64
  11.     64 bits ( 8 bytes)
  12.  
  13. float32
  14.     32 bits (4 bytes)
  15. float64
  16.     64 bits (8 bytes)
  17.  
  18. bool
  19.     8 bits (1 byte)
  20.  
  21. string
  22.     128 bits ( 16 bytes)
  23.  
  24. While reading data, a modern computer’s CPU’s internal data registers can hold and process 64-bits. This is called the word size. It is usually 32-bit or 64-bit.
  25. When a struct is created in Go, a contiguous block of memory for it is allocated.
  26.  
  27. Quindi se i blocchi sono contigui e da 64 bit ovvero 8 bytes dovremmo scrivere le struct organizzandole con variabili che entrano in blocchi da 64 senza lasciare gap.
  28.  
  29. type Dog struct {
  30.     Age uint8
  31.     Hunger int64
  32.     Happy bool
  33. }
  34.  
  35. Age is a 8 bit integer
  36. Hunger is a 64 bit integer
  37. Happy is a boolean, which is 8 bits.
  38.  
  39. We expect the size of the Dog struct to be 80 bits. In reality it is 192 bits.
  40. Age is 8 bits, but padding is needed since next field is 64 bits and there is no room for it. 8 bit + 56 bit padding
  41. Hunger takes all 64 bit + 0 bit padding
  42. Happy is 8 bits, but it also needs padding to complete the word size.8 bit + 56 bit padding
  43. We have wasted 112 bits.
  44.  
  45. */
  46.  
  47. package main
  48.  
  49. import (
  50.     "fmt"
  51.     "unsafe"
  52. )
  53.  
  54. type Dog struct {
  55.     Age uint8
  56.     Hunger int64
  57.     Happy bool
  58. }
  59.  
  60.  
  61. type OptimizedDog struct {
  62.     Hunger int64
  63.     Age uint8
  64.     Happy bool
  65. }
  66.  
  67. func main() {
  68.     dog := &Dog{
  69.         Age:    4,
  70.         Hunger: 20,
  71.         Happy:  true,
  72.     }
  73.     optimizedDog := &OptimizedDog{
  74.         Hunger: 20,
  75.         Age:    4,
  76.         Happy:  true,
  77.     }
  78.     fmt.Printf("Size: %d\n", unsafe.Sizeof(*dog)) // 24 bytes
  79.     fmt.Printf("Size: %d\n", unsafe.Sizeof(*optimizedDog)) // 16 bytes
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement