What are the advantages of the general types (int / uint) over specific types (int64 / uint64) in Go lang?

前端 未结 3 798
温柔的废话
温柔的废话 2021-01-04 08:38

I understand that int and uint are 64bit signed / unsigned integers - just like int64 / uint64. And I also understand tha

相关标签:
3条回答
  • 2021-01-04 08:56

    In addition to int being of "native" size slice and array indices are int and not int64 or int32.

    0 讨论(0)
  • 2021-01-04 09:02

    int and uint are only 64-bit on 64-bit architectures. On 32-bit architectures they are 32 bits.

    The general answer is that, unless you need a certain precision, sticking with datatypes that are the same size as a word on the current architecture (e.g. 32 bits on a 32-bit architecture) is typically slightly more efficient.

    0 讨论(0)
  • 2021-01-04 09:13

    int and uint correspond to the maximum possible length of basic Go data structures in a Go implementation and runtime. The length of string, map[K]T, []T and chan T always fits into an int, and the capacity of []T and chan T always fits into an int.

    An allocation via make is bound to return an object with length and capacity that always fit into an int. The built-in function append returns a slice with length and capacity that never exceed an int. The length (the number of defined keys) of a map after inserting a new key-value pair always fits into an int.

    The main benefit is that int and uint are the smallest (in terms of bitsize) data types which are safe to use in a Go program in conjunction with common Go data types such as slices and maps.

    The size of int is independent from the size of a pointer *T. The integer type corresponding to *T is uintptr. In theory, a Go implementation could choose to map int to int16 - many Go programs would remain to work correctly, but limiting the size of allocations to 15 bits may be too restrictive and would cause runtime panics.

    On 64-bit architectures Go 1.0 has int and uint 32 bits long, Go 1.1 64 bits long (see Go 1.1 Release Notes). This change will increase the memory usage of some Go programs on 64-bit architectures..

    Explicitly using int64 instead of int in a Go program can make it slower under Go 1.0 and on 32-bit architectures because:

    • of conversions between int and int64

    • the performance of certain CPU instructions, such as division, depends on the size of operands

    Explicitly using int64 instead of int in a Go program can make it faster under Go 1.0 on 64-bit architectures because:

    • The compiler can generate more efficient code for address and offset computation if all operands are 64-bit. Mixing 32-bit and 64-bit operands when computing addresses and offsets is slower.

    Using uint16 as an index when accessing [1<<16]T allows the compiler to remove bound checking instructions.

    0 讨论(0)
提交回复
热议问题