Backend Development 24 min read

Function Call Mechanisms in Go and Performance Optimization

The article explains Go’s caller‑callee model, stack‑frame layout, and how parameter and return‑value passing shifted in Go 1.17.1—using registers for up to nine arguments or results and the stack for any beyond—highlighting the impact on performance and optimization.

Tencent Cloud Developer
Tencent Cloud Developer
Tencent Cloud Developer
Function Call Mechanisms in Go and Performance Optimization

导读|腾讯后台开发工程师涂明光将带你由浅入深了解函数调用,并结合不同版本Go进行实操解答。

1)调用者caller与被调用者callee

如果一个函数调用另外一个函数,那么该函数被称为调用者函数,也叫做caller,而被调用的函数称为被调用者函数,也叫做callee。比如函数main中调用sum函数,那么main就是caller,而sum函数就是callee。

2)函数栈和函数栈帧

函数执行时需要有足够的内存空间,供它存放局部变量、参数等数据,这段空间对应到虚拟地址空间的栈,也即函数栈。在现代主流机器架构上(例如x86)中,栈都是向下生长的。栈的增长方向是从高位地址到地位地址向下进行增长。

3)分配给一个个函数的栈空间被称为“函数栈帧”。在Go语言中函数栈帧布局是这样的:先是调用者caller栈基地址,然后是调用者函数caller的局部变量、接着是被调用函数callee的返回值和参数。然后是被调用者callee的栈帧。

4)Go1.17.1之前版本,参数完全通过栈传递;参数列表从右至左依次压栈。

5)Go1.17.1版本,9个以内的参数通过寄存器传递,9个以外的通过栈上传递。

6)Go1.17.1之前版本,callee函数返回值通过caller栈传递;Go1.17.1以后,函数调用的返回值,9个以内通过寄存器传递回caller,9个以外在栈上传递。

7)综上,在Go1.17.1版本的函数调用中,参数传递使用了多个寄存器,并且被调用方callee的返回值由callee本身的栈帧负责存放,而不是放在caller的栈帧上;当callee的栈帧被销毁时,其返回值通过AX,BX等寄存器传递给调用方caller。

8)9个以内的参数通过寄存器传递,9个以外的通过栈上传递。

9)9个以内的返回值通过寄存器传递,9个以外在栈上传递。

Performancebackend developmentGoassemblyfunction callsStack vs Registers
Tencent Cloud Developer
Written by

Tencent Cloud Developer

Official Tencent Cloud community account that brings together developers, shares practical tech insights, and fosters an influential tech exchange community.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.