is the storage space for go local variables a heap or a stack?

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

is the storage space for go local variables a heap or a stack?

The compiler automatically chooses to allocate storage space on the stack or on the heap for local variables, but it may be surprising that the choice is not determined by the way Var or new declares variables.

var global *intfunc f() {    var x int    x = 1    global = &x}func g() {    y := new(int)    *y = 1}

The x variable in the F function must be allocated on the heap, because it can still be found by the package-level global variable after the function exits, although it is defined inside the function, and in the terms of the go language, the x local variable escapes from the function f . Conversely, when the G function returns, the variable y will be unreachable, meaning it can be recycled immediately. As a result,y does not escape from function g, and the compiler can choose to allocate *y storage space on the stack (you can also choose to allocate on the heap, and then the memory space of the variable is reclaimed by the Go-language GC), although the new method is used here. In fact, at any time, you do not need to consider the escape behavior of variables in order to write the correct code, keep in mind that the escaped variables require additional memory allocation, while the performance of the optimization may have a subtle impact.

The go language's automatic garbage collector is a great help in writing the right code, but it doesn't mean you don't have to think about memory at all. You do not need to explicitly allocate and free memory, but to write efficient programs you still need to understand the life cycle of the variables. For example, if you save a pointer to a short life cycle object to an object with a long life cycle, especially when you save to a global variable, garbage collection of short life cycle objects (which can affect program performance) is blocked.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.