performancegostructsizeof

size of a struct in Go without initialising a variable of struct


There is one huge struct in our code, and its being passed around everywhere as a value. I would like to be able to know the size(amount of memory in bytes, go will allocate for a variable of this struct), without incurring the overhead of initialising a dummy value.

Is there a way to do that in golang?

In C we have the sizeof compile-time unary operator, that can do this.

Note : This is not the duplicate of Sizeof struct in Go, because in my case I cant use unsafe.Sizeof(<variable>) or reflect.ValueOf(<variable>).Type().Size() because they need a variable or a literal to be initialised


Solution

  • Use answers in Sizeof struct in Go, but start with a nil pointer to the type:

    type Coord3d struct {
        X, Y, Z int64
    }
    
    // Option 1:
    
    ptrType := reflect.TypeFor[*Coord3d]()
    valueType := ptrType.Elem()
    size := valueType.Size()
    fmt.Println(size)  // prints 24
    
    // Option 2:
    
    size = unsafe.Sizeof(*(*Coord3d)(nil))
    fmt.Println(size) // prints 24
    

    https://play.golang.com/p/Bj8hvQ3aPeP

    The simplest and most efficient approach is to rely on compiler optimizations.

    size = unsafe.Sizeof(Coord3d{})
    fmt.Println(size) // prints 24
    

    Because the value of Coord3d{} is not used, the compiler does not allocate it.