zoukankan      html  css  js  c++  java
  • golang中的内存逃逸

    关于golang的变量是定义在堆上还是栈上,官方的解释如下

    How do I know whether a variable is allocated on the heap or the stack?

    From a correctness standpoint, you don't need to know. Each variable in Go exists as long as there are references to it. The storage location chosen by the implementation is irrelevant to the semantics of the language.

    The storage location does have an effect on writing efficient programs. When possible, the Go compilers will allocate variables that are local to a function in that function's stack frame. However, if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors. Also, if a local variable is very large, it might make more sense to store it on the heap rather than the stack.

    In the current compilers, if a variable has its address taken, that variable is a candidate for allocation on the heap. However, a basic escape analysis recognizes some cases when such variables will not live past the return from the function and can reside on the stack.

    大概总结如下:

    1、指针逃逸 - 方法返回局部变量指针,就形成变量逃逸

    2、栈空间不足逃逸 - 当切片长度扩大到10000时就会逃逸,实际上当栈空间不足以存放当前对象或无法判断当前切片长时会将对象分配到堆中

    3、动态类型逃逸 - 编译期间很难确定其参数的具体类型,也能产生逃逸度

    4、闭包引用对象逃逸 - 原本属于局部变量,由于闭包的引用,不得不放到堆上,以致产生逃逸

    5、跨协程引用对象逃逸 - 原本属于A协程的变量,通过指针传递给B协程使用,产生逃逸

  • 相关阅读:
    Eclipse扩展安装插件方式
    Tomcat通过JNDI方式链接MySql数据库
    ArrayList实现根据某属性大小相间排序
    JMeter 怎么保存登录状态
    JMeter怎么使用代理服务器
    JMeter模拟多个用户进行登录
    JMeter怎么在get URL请求、POST请求中添加动态参数用于服务器段安全验证
    (转)sizeof()和_countof()区别
    潜心修炼, 生活,会给你一个惊喜~
    最初的梦想
  • 原文地址:https://www.cnblogs.com/kirachen/p/12402396.html
Copyright © 2011-2022 走看看