When optimizing a Go application, one way is, with help from the debugger, to reduce the number of heap allocations. This is somewhat of a guess work, and it’s also not explicit when reading the code if a variable will be stack or heap allocated. I had an idea of an experimental language feature that could remedy this.
Example:
// v1 is either stack or heap allocated depending on context
v1 := Point{1, 2}
// v2 is always stack allocated, but is NOT allowed to escape
local v2 := Point{1, 2}
The crucial point is “not allowed to escape”. Go is already using escape analysis to decide what can be stack allocated. It’s a common optimization technique in many languages. Adding local
would throw an error during compile-time if a variable was detected to escape (in principle, if the variable or its memory area can still be referenced when the current scope disappears).
This feature is kind of similar to what they’re doing in Rust with lifetimes. Lifetimes are more powerful but also puts a greater burden on the programmer. Non-escaping variables would give the programmer the possibility to “opt out” of garbage collection in a predictable manner, in tight spots where optimal performance is required, instead of playing Whac-a-mole with the debugger.
Non-escaping is not the same as non-aliasing, btw. Compare with the uniqueness type.
Non-escaping variables can still be passed down the stack chain using references, but not up (can’t be returned without a copy (this copy might be optimized away by the compiler, as done in C)).
There are other optimization techniques related to escape analysis that are not considered by this idea, e.g. scalar replacement.
Another way to opt out of GC are value types in C# (not yet added to Java). It’s somewhat ad hoc. Value types are implicitly copied, as they are in Rust and C (some of those copy instructions can be optimized by the compiler).
One possible prototype implementation would be to make a Go parser that compiles to Go, but adding the new keyword (removed after compiled) together with the escape analysis on the abstract syntax tree.
Let me know what you think.
Olle