Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much memory is allocated for int8, int16 and int32 in Golang? [duplicate]

Tags:

go

I have a simple piece of code where I allocate memory for int8, int16, int32 and int64 types and print out the addresses of the variables:

package main

import (

"fmt"
"runtime"
)

func main() {

    fmt.Println(runtime.Compiler, runtime.GOARCH, runtime.GOOS)

    var i8 *int8
    var i16 *int16
    var i32 *int32
    var i64 *int64

    fmt.Println(&i8)
    fmt.Println(&i16)
    fmt.Println(&i32)
    fmt.Println(&i64)

}

Here is the output I receive:

gc amd64 darwin
0xc00008a020
0xc00008a028
0xc00008a030
0xc00008a038

From here I may conclude that only int16 is using 4 bytes, the other types are using 8 bytes.

Are both my reasoning and the method of checking the allocated memory size correct?

If yes, what would be the advantages of using int8, int32 on a 64-bit architecture system?

like image 292
vvraskin Avatar asked Dec 08 '18 13:12

vvraskin


1 Answers

You are allocating pointers which are all 8 bytes in your example: gc amd64 darwin.

For your example,

package main

import (
    "fmt"
    "runtime"
    "unsafe"
)

func main() {

    fmt.Println(runtime.Compiler, runtime.GOARCH, runtime.GOOS)

    var i8 *int8
    var i16 *int16
    var i32 *int32
    var i64 *int64

    fmt.Println(&i8, unsafe.Sizeof(i8), unsafe.Sizeof(*i8))
    fmt.Println(&i16, unsafe.Sizeof(i16), unsafe.Sizeof(*i16))
    fmt.Println(&i32, unsafe.Sizeof(i32), unsafe.Sizeof(*i32))
    fmt.Println(&i64, unsafe.Sizeof(i64), unsafe.Sizeof(*i64))

}

Output:

gc amd64 linux
0xc00000e030 8 1
0xc00000e038 8 2
0xc00000e040 8 4
0xc00000e048 8 8

For CPU operations it is often most efficient to use the natural word size of the CPU, for example, int or int64 on amd64.

For memory size, for a large number of integers, it can be most efficient to use the smallest integer size that can hold the range of values.

It's a balancing act. Benchmark real code from real applications.

like image 122
peterSO Avatar answered Nov 20 '22 18:11

peterSO