8

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?

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
vvraskin
  • 368
  • 6
  • 13
  • @peterSO yeap, you are right! changing it to actual values - returned a more promising result: gc amd64 darwin 0xc000076018 0xc00007601a 0xc00007601c 0xc000076030 – vvraskin Dec 08 '18 at 13:22

1 Answers1

9

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.

peterSO
  • 158,998
  • 31
  • 281
  • 276