Golang Tips: The spatial cost of passing various types of parameters

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

When a function is called, the value of the argument is copied to the parameter.

For int32,uint64 such as INTN,UINTN type, the cost of passing is obvious, for example, passing a int32 requires 4 bytes. int and uint are platform-dependent, both 4-byte (32-bit) or 8-byte (64-bit), and uintptr and any type of pointer are 4-byte (32-bit) or 8-byte (64-bit). Float32 and Float64 require 4 bytes and 8 bytes respectively, and complex64 and complex128 are equivalent to two float32 and two float64 respectively.

String (string), slice (slice), interface (interface), dictionary (map), channel is not so obvious, but by letting go generate C library to see some clues.

A header file (. h) is automatically generated when go generates a C library, and some of the contents are as follows:

typedef struct {char *p; Goint N; } gostring;typedef void *gomap;typedef void *gochan;typedef struct {void *t; void *v;} gointerface;typedef struct {void *data; Goint Len; Goint cap; } Goslice;

Among them, goint in 32-bit and 64-bit respectively equivalent (C language) int32_t and Int64_t,gouint similar.

This shows that when go passes a string, the cost of passing is equivalent to a pointer and a (GO) int. Of course, if you modify the string parameter in the body of the function, go will generate a (deep) copy of the string.

Passing a map or Chan is equivalent to passing a pointer, so the cost of passing them is very small and high performance.

The cost of passing a interface is two pointers (possibly an identity type, an identity method set).

The cost of passing a slice is a pointer plus two (GO) int.


Arrays and structs:

The go array is purely a value type, and the cost of passing a [n]t is N T.

The cost of passing a struct is the sum of the size of each field (the alignment problem is not considered).

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.