Does anybody know how to get memory size of the variable (int
, string
, []struct
, etc) and print it? Is it possible?
var i int = 1 //I want to get something like this: fmt.Println("Size of i is: %?", i) //Also, it would be nice if I could store the value into a string
The size of a variable depends on its type, and C++ has a very convenient operator called sizeof that tells you the size in bytes of a variable or a type. The usage of sizeof is simple. To determine the size of an integer, you invoke sizeof with parameter int (the type) as demonstrated by Listing 3.5.
Use sys. getsizeof to get the size of an object, in bytes.
One way to get an estimate of an object's size in Java is to use getObjectSize(Object) method of the Instrumentation interface introduced in Java 5. As we could see in Javadoc documentation, the method provides “implementation-specific approximation” of the specified object's size.
You can use the unsafe.Sizeof function for this. It returns the size in bytes, occupied by the value you pass into it. Here's a working example:
package main import "fmt" import "unsafe" func main() { a := int(123) b := int64(123) c := "foo" d := struct { FieldA float32 FieldB string }{0, "bar"} fmt.Printf("a: %T, %d\n", a, unsafe.Sizeof(a)) fmt.Printf("b: %T, %d\n", b, unsafe.Sizeof(b)) fmt.Printf("c: %T, %d\n", c, unsafe.Sizeof(c)) fmt.Printf("d: %T, %d\n", d, unsafe.Sizeof(d)) }
Take note that some platforms explicitly disallow the use of unsafe, because it is.. well, unsafe. This used to include AppEngine. Not sure if that is still the case today, but I imagine so.
As @Timur Fayzrakhmanov notes, reflect.TypeOf(variable).Size()
will give you the same information. For the reflect
package, the same restriction goes as for the unsafe
package. I.e.: some platforms may not allow its use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With