Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- int/uint
- either 32 bits (4 bytes) or 64 bits (8 bytes)
- int8/uint8
- 8 bits (1 byte)
- int16/uint16
- 16 bits (2 bytes)
- int32/uint32
- 32 bits (4 bytes)
- int64/uint64
- 64 bits ( 8 bytes)
- float32
- 32 bits (4 bytes)
- float64
- 64 bits (8 bytes)
- bool
- 8 bits (1 byte)
- string
- 128 bits ( 16 bytes)
- 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.
- When a struct is created in Go, a contiguous block of memory for it is allocated.
- 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.
- type Dog struct {
- Age uint8
- Hunger int64
- Happy bool
- }
- Age is a 8 bit integer
- Hunger is a 64 bit integer
- Happy is a boolean, which is 8 bits.
- We expect the size of the Dog struct to be 80 bits. In reality it is 192 bits.
- 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
- Hunger takes all 64 bit + 0 bit padding
- Happy is 8 bits, but it also needs padding to complete the word size.8 bit + 56 bit padding
- We have wasted 112 bits.
- */
- package main
- import (
- "fmt"
- "unsafe"
- )
- type Dog struct {
- Age uint8
- Hunger int64
- Happy bool
- }
- type OptimizedDog struct {
- Hunger int64
- Age uint8
- Happy bool
- }
- func main() {
- dog := &Dog{
- Age: 4,
- Hunger: 20,
- Happy: true,
- }
- optimizedDog := &OptimizedDog{
- Hunger: 20,
- Age: 4,
- Happy: true,
- }
- fmt.Printf("Size: %d\n", unsafe.Sizeof(*dog)) // 24 bytes
- fmt.Printf("Size: %d\n", unsafe.Sizeof(*optimizedDog)) // 16 bytes
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement