一文弄清楚Golang内存逃逸
ztj100 2025-01-11 18:53 14 浏览 0 评论
1. 为什么要了解内存逃逸
c/c++的programmer对于堆内存、栈内存一定非常熟悉,以为内存管理完全由使用者自己管理。Go语言的内存管理完全由Go的runtime接管,那么是不程序员就完全不用care变量是如何分配的呢?
- 减少了gc压力。如果变量都分配到堆上,堆不像栈可以自动清理。它会引起Go频繁地进行垃圾回收,而垃圾回收会占用比较大的系统开销,甚至会导致STW(stop the world)。
- 提高分配效率。堆和栈相比,堆适合不可预知大小的内存分配。但是为此付出的代价是分配速度较慢,而且会形成内存碎片。栈内存分配则会非常快。但当我们的服务发现性能瓶颈,要如何去定位瓶颈,让我们的程序运行的更快,就非常有必要了解Go的内存分配。
2. 什么是内存逃逸
Go语言中局部的非指针变量通常是不受GC管理的,这种Go变量的内存分配称为“栈分配”,处于goroutine自己的栈中。由于Go编译器无法确定其生命周期,因此无法以这种方式分配内存的Go变量会逃逸到堆上,被称为 内存逃逸 。
3. 哪些情况下会发生内存逃逸
先来说一下通过go编译器查看内存逃逸方式go build -gcflags=-m xxx.go
- 局部变量被返回造成逃逸
package main
type User struct {
Namestring
}
func foo(s string) *User {
u := new(User)
u.Name= s
return u // 方法内局部变量返回,逃逸
}
func main() {
user := foo("hui")
user.Name= "dev"
}
//# command-line-arguments
//./escape.go:7:6: can inline foo
//./escape.go:13:6: can inline main
//./escape.go:14:13: inlining call to foo
//./escape.go:7:10: leaking param: s
//./escape.go:8:10: new(User) escapes to heap
//./escape.go:14:13: new(User) does not escape
- interface{}动态类型 逃逸
package main
import "fmt"
func main() {
name := "devhui"
fmt.Println(name)
}
//# command-line-arguments
//./escape_02.go:7:13: inlining call to fmt.Println
//./escape_02.go:7:13: name escapes to heap
//./escape_02.go:7:13: []interface {}{...} does not escape
//<autogenerated>:1: leaking param content: .this
很多函数的参数为interface{} 空接口类型,这些都会造成逃逸。比如
func Printf(format string, a ...interface{}) (n int, err error)
func Sprintf(format string, a ...interface{}) string
func Fprint(w io.Writer, a ...interface{}) (n int, err error)
func Print(a ...interface{}) (n int, err error)
func Println(a ...interface{}) (n int, err error)
复制代码
编译期间很难确定其参数的具体类型,也能产生逃逸
func main() {
fmt.Println("hello 逃逸")
}
/* 逃逸日志分析
./main.go:5:6: can inline main
./main.go:6:13: inlining call to fmt.Println
./main.go:6:14: "hello 逃逸" escapes to heap
./main.go:6:13: []interface {} literal does not escape
*/
- 栈空间不足逃逸
package main
func main() {
s := make([]int, 1000, 1000)
for index, _ := range s {
s[index] = index
s1 := make([]int, 10000, 10000)
for index, _ := range s1 {
s1[index] = index
}
}
逃逸分析:
./escape_03.go:4:11: make([]int, 1000, 1000) does not escape
./escape_03.go:9:12: make([]int, 10000, 10000) escapes to heap
s足够在栈空间分配没有逃逸;s1空间不够在栈内分配发生了逃逸。
- 变量大小不确定(如 slice 长度或容量不定)
package main
func main() {
s := make([]int, 0, 1000)
for index, _ := range s {
s[index] = index
}
num := 1000
s1 := make([]int, 0, num)
for index, _ := range s1 {
s1[index] = index
}
}
逃逸分析:
./escape_05.go:4:11: make([]int, 0, 1000) does not escape
./escape_05.go:10:12: make([]int, 0, num) escapes to heap
s分配时cap是一个常量没有发生逃逸,s1的cap是一个变量发生了逃逸。
- 闭包
func Increase() func() int {
n := 0
return func() int {
n++
return n
}
}
func main() {
in := Increase()
fmt.Println(in()) // 1
fmt.Println(in()) // 2
}
//./escape_04.go:6:2: moved to heap: n
//./escape_04.go:7:9: func literal escapes to heap
//./escape_04.go:7:9: func literal does not escape
//./escape_04.go:15:16: int(~R0) escapes to heap
//./escape_04.go:15:13: []interface {}{...} does not escape
//./escape_04.go:16:16: int(~R0) escapes to heap
//./escape_04.go:16:13: []interface {}{...} does not escape
//<autogenerated>:1: leaking param content: .this
4. 如何减少逃逸
- 局部切片尽可能确定长度或容量
- benchmark test
import "testing"
// sliceEscape 发生逃逸,在堆上申请切片
func sliceEscape() {
number := 10
s1 := make([]int, 0, number)
for i := 0; i < number; i++ {
s1 = append(s1, i)
}
}
// sliceNoEscape 不逃逸,限制在栈上
func sliceNoEscape() {
s1 := make([]int, 0, 10)
for i := 0; i < 10; i++ {
s1 = append(s1, i)
}
}
func BenchmarkSliceEscape(b *testing.B) {
for i := 0; i < b.N; i++ {
sliceEscape()
}
}
func BenchmarkSliceNoEscape(b *testing.B) {
for i := 0; i < b.N; i++ {
sliceNoEscape()
}
}
- 测试结果:
BenchmarkSliceEscape
BenchmarkSliceEscape-10 53271513 22.09 ns/op
BenchmarkSliceNoEscape
BenchmarkSliceNoEscape-10 187033111 6.458 ns/op
- 合理选择返回值、返回指针
- 返回指针可以避免值的拷贝,但是会导致内存分配逃逸到堆中,增加GC的负担。
- 一般情况下,对于需要修改原对象,或占用内存比较大的对象,返回指针。对于只读或占用内存较小的对象,返回值能够获得更好的性能。
- benchmark test
package escape_bench_02
import "testing"
type St struct {
arr [100]int
}
func retValue() St {
var st St
return st
}
func retPtr() *St {
var st St
return &st
}
func BenchmarkRetValue(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = retValue()
}
}
func BenchmarkRetPtr(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = retPtr()
}
}
- 测试结果
BenchmarkRetValue-10 34714424 34.45 ns/op 0 B/op 0 allocs/op
BenchmarkRetPtr-10 8038676 145.3 ns/op 896 B/op 1 allocs/op
可以看到返回值更快且没有发生堆内存的分配。
- 小的拷贝好过引用
- benchmark test
package escape_bench_03
import "testing"
const capacity = 1024
func arrayFibonacci() [capacity]int {
var d [capacity]int
for i := 0; i < len(d); i++ {
if i <= 1 {
d[i] = 1
continue
}
d[i] = d[i-1] + d[i-2]
}
return d
}
func sliceFibonacci() []int {
d := make([]int, capacity)
for i := 0; i < len(d); i++ {
if i <= 1 {
d[i] = 1
continue
}
d[i] = d[i-1] + d[i-2]
}
return d
}
func BenchmarkArray(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = arrayFibonacci()
}
}
func BenchmarkSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = sliceFibonacci()
}
}
- 测试结果:
BenchmarkArray-10 346110 2986 ns/op 0 B/op 0 allocs/op
BenchmarkSlice-10 389745 2849 ns/op 8192 B/op 1 allocs/op
那么多大的变量才算是小变量呢? 对 Go 编译器而言,超过一定大小的局部变量将逃逸到堆上,不同 Go 版本的大小限制可能不一样。一般是 < 64KB,局部变量将不会逃逸到堆上。
- 返回值使用确定的类型
- benchmark test
package escape_bench_04
import "testing"
const capacity = 1024
func returnArray() [capacity]int {
var arr [capacity]int
for i := 0; i < len(arr); i++ {
arr[i] = 1000
}
return arr
}
func returnInterface() interface{} {
var arr [capacity]int
for i := 0; i < len(arr); i++ {
arr[i] = 1000
}
return arr
}
func BenchmarkReturnArray(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = returnArray()
}
}
func BenchmarkReturnInterface(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = returnInterface()
}
}
- 测试结果
相关推荐
- Whoosh,纯python编写轻量级搜索工具
-
引言在许多应用程序中,搜索功能是至关重要的。Whoosh是一个纯Python编写的轻量级搜索引擎库,可以帮助我们快速构建搜索功能。无论是在网站、博客还是本地应用程序中,Whoosh都能提供高效的全文搜...
- 如何用Python实现二分搜索算法(python二分法查找代码)
-
如何用Python实现二分搜索算法二分搜索(BinarySearch)是一种高效的查找算法,适用于在有序数组中快速定位目标值。其核心思想是通过不断缩小搜索范围,每次将问题规模减半,时间复杂度为(O...
- 路径扫描 -- dirsearch(路径查找器怎么使用)
-
外表干净是尊重别人,内心干净是尊重自己,干净,在今天这个时代,应该是一种极高的赞美和珍贵。。。----网易云热评一、软件介绍Dirsearch是一种命令行工具,可以强制获取web服务器中的目录和文件...
- 78行Python代码帮你复现微信撤回消息!
-
来源:悟空智能科技本文约700字,建议阅读5分钟。本文基于python的微信开源库itchat,教你如何收集私聊撤回的信息。...
- 从零开始学习 Python!2《进阶知识》 Python进阶之路
-
欢迎来到Python学习的进阶篇章!如果你说已经掌握了基础语法,那么这篇就是你开启高手之路的大门。我们将一起探讨面向对象编程...
- 白帽黑客如何通过dirsearch脚本工具扫描和收集网站敏感文件
-
一、背景介绍...
- Python之txt数据预定替换word预定义定位标记生成word报告(四)
-
续接Python之txt数据预定替换word预定义定位标记生成word报告(一)https://mp.toutiao.com/profile_v4/graphic/preview?pgc_id=748...
- Python——字符串和正则表达式中的反斜杠('\')问题详解
-
在本篇文章里小编给大家整理的是关于Python字符串和正则表达式中的反斜杠('\')问题以及相关知识点,有需要的朋友们可以学习下。在Python普通字符串中在Python中,我们用'\'来转义某些普通...
- Python re模块:正则表达式综合指南
-
Python...
- python之re模块(python re模块sub)
-
re模块一.re模块的介绍1.什么是正则表达式"定义:正则表达式是一种对字符和特殊字符操作的一种逻辑公式,从特定的字符中,用正则表达字符来过滤的逻辑。(也是一种文本模式;)2、正则表达式可以帮助我们...
- MySQL、PostgreSQL、SQL Server 数据库导入导出实操全解
-
在数字化时代,数据是关键资产,数据库的导入导出操作则是连接数据与应用场景的桥梁。以下是常见数据库导入导出的实用方法及代码,包含更多细节和特殊情况处理,助你应对各种实际场景。一、MySQL数据库...
- Zabbix监控系统系列之六:监控 mysql
-
zabbix监控mysql1、监控规划在创建监控项之前要尽量考虑清楚要监控什么,怎么监控,监控数据如何存储,监控数据如何展现,如何处理报警等。要进行监控的系统规划需要对Zabbix很了解,这里只是...
- mysql系列之一文详解Navicat工具的使用(二)
-
本章内容是系列内容的第二部分,主要介绍Navicat工具的使用。若查看第一部分请见:...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- Whoosh,纯python编写轻量级搜索工具
- 如何用Python实现二分搜索算法(python二分法查找代码)
- 路径扫描 -- dirsearch(路径查找器怎么使用)
- 78行Python代码帮你复现微信撤回消息!
- 从零开始学习 Python!2《进阶知识》 Python进阶之路
- 白帽黑客如何通过dirsearch脚本工具扫描和收集网站敏感文件
- Python之txt数据预定替换word预定义定位标记生成word报告(四)
- 假期苦短,我用Python!这有个自动回复拜年信息的小程序
- Python——字符串和正则表达式中的反斜杠('\')问题详解
- Python re模块:正则表达式综合指南
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- node卸载 (33)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- exceptionininitializererror (33)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)