Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get memory size of variable?

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 
like image 977
Timur Fayzrakhmanov Avatar asked Nov 17 '14 15:11

Timur Fayzrakhmanov


People also ask

How do you find the size of a variable?

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.

How do you find the memory size of a variable in Python?

Use sys. getsizeof to get the size of an object, in bytes.

How do you find the size of a variable in Java?

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.


1 Answers

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.

like image 129
jimt Avatar answered Sep 30 '22 13:09

jimt