dongzhi5846 2019-01-11 19:16
浏览 7

gc Go如何处理堆分配?

Does gc Go (specifically go1.11) pre-allocates a chunk of memory and take from it for each allocation (like JVM), or it allocates every time a variable is created, and is it a kernel call (malloc)?

If it is one kernel call per allocation, that would make variable creation expensive. How can I force allocation on the stack/heap?

  • 写回答

1条回答 默认 最新

  • douhao3562 2019-01-12 13:06
    关注

    This is covered in various places, like the FAQ:

    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.


    Go's memory allocation is carefully optimized for its needs, for example with a custom malloc. I suspect you have a slightly different underlying question/problem that you're struggling with - it would be better to ask that instead. If this is just exploration/curiosity, you'll have to make your question much more specific.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?