How to get the size of a structure and its contents in bytes in golang?

I have a structure, say:

type ASDF struct { A uint64 B uint64 C uint64 D uint64 E uint64 F string } 

I create a slice of this structure: a := []ASDF{}

I perform operations on this fragment of the structure (adding / removing / updating structures that differ in content); How can I get the total size in bytes (for memory) of the slice and its contents? Is there a built-in function for this, or do I need to manually perform the calculation using unsafe.Sizeof , and then len each line?

+5
source share
2 answers

Summarize the size of all memory, excluding the garbage collector and other overhead. For instance,

 package main import ( "fmt" "unsafe" ) type ASDF struct { A uint64 B uint64 C uint64 D uint64 E uint64 F string } func (s *ASDF) size() int { size := int(unsafe.Sizeof(*s)) size += len(sF) return size } func sizeASDF(s []ASDF) int { size := 0 s = s[:cap(s)] size += cap(s) * int(unsafe.Sizeof(s)) for i := range s { size += (&s[i]).size() } return size } func main() { a := []ASDF{} b := ASDF{} bA = 1 bB = 2 bC = 3 bD = 4 bE = 5 bF = "ASrtertetetetetetetDF" fmt.Println((&b).size()) a = append(a, b) c := ASDF{} cA = 10 cB = 20 cC = 30 cD = 40 cE = 50 cF = "ASetDF" fmt.Println((&c).size()) a = append(a, c) fmt.Println(len(a)) fmt.Println(cap(a)) fmt.Println(sizeASDF(a)) } 

Output:

 69 54 2 2 147 

http://play.golang.org/p/5z30vkyuNM

+6
source

I'm afraid to say that unsafe.Sizeof is the way to go here if you want to get any result at all. The size of the structure in memory is something you should not rely on. Note that even the result of unsafe.Sizeof is inaccurate: the runtime may add headers to data that you cannot observe to help garbage collection.

In your specific example (looking for cache size), I suggest you go with a static size that is reasonable for many processors. In almost all cases, such microoptimizations are not going to pay.

+1
source

All Articles