Skip to content

Instantly share code, notes, and snippets.

@earayu
Created May 4, 2023 04:32
Show Gist options
  • Save earayu/d763af07d3db1a69fe7ea88fd9d349f0 to your computer and use it in GitHub Desktop.
Save earayu/d763af07d3db1a69fe7ea88fd9d349f0 to your computer and use it in GitHub Desktop.
memo

考虑这个问题: 在Golang的函数中创建一个struct,然后将它return,这个struct的内存空间会被分配在哪里?return的时候会有哪些操作?是否会发生拷贝?

有关go内存是在堆上分配的,还是在栈上分配的,这个是在编译过程中,通过逃逸分析来确定的,其主体思想是: 假设有变量v,及指向v的指针p,如果p的生命周期大于v的生命周期,则v的内存要在堆上分配。 https://cloud.tencent.com/developer/article/1861199

小技巧:我们也可以在编译时,通过加上-m参数,来让编译器告诉我们,一个变量到底是分配在堆上,还是在栈上

问题:函数返回pointer高效,还是返回struct高效? 经过测试,1MiB字节以下,返回结构体都更有优势。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment